<!DOCTYPE HTML>
<html lang="en">


<head>
    <meta charset="utf-8">
    <meta name="keywords" content="AverageJoe&#39;s Blog">
    <meta name="description" content="this is my secret garden where I sow my inspirations.">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
    <meta name="renderer" content="webkit|ie-stand|ie-comp">
    <meta name="mobile-web-app-capable" content="yes">
    <meta name="format-detection" content="telephone=no">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
    <!-- Global site tag (gtag.js) - Google Analytics -->


    <title>AverageJoe&#39;s Blog</title>
    <link rel="icon" type="image/png" href="/favicon.png">

    <link rel="stylesheet" type="text/css" href="/libs/awesome/css/all.css">
    <link rel="stylesheet" type="text/css" href="/libs/materialize/materialize.min.css">
    <link rel="stylesheet" type="text/css" href="/libs/aos/aos.css">
    <link rel="stylesheet" type="text/css" href="/libs/animate/animate.min.css">
    <link rel="stylesheet" type="text/css" href="/libs/lightGallery/css/lightgallery.min.css">
    <link rel="stylesheet" type="text/css" href="/css/matery.css">
    <link rel="stylesheet" type="text/css" href="/css/my.css">

    <script src="/libs/jquery/jquery.min.js"></script>
<meta name="generator" content="Hexo 5.0.0"><link rel="alternate" href="/atom.xml" title="AverageJoe's Blog" type="application/atom+xml">
</head>


<body>
    <header class="navbar-fixed">
    <nav id="headNav" class="bg-color nav-transparent">
        <div id="navContainer" class="nav-wrapper container">
            <div class="brand-logo">
                <a href="/" class="waves-effect waves-light">
                    
                    <img src="/medias/logo.png" class="logo-img" alt="LOGO">
                    
                    <span class="logo-span">AverageJoe&#39;s Blog</span>
                </a>
            </div>
            

<a href="#" data-target="mobile-nav" class="sidenav-trigger button-collapse"><i class="fas fa-bars"></i></a>
<ul class="right nav-menu">
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/" class="waves-effect waves-light">
      
      <i class="fas fa-home" style="zoom: 0.6;"></i>
      
      <span>Index</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/tags" class="waves-effect waves-light">
      
      <i class="fas fa-tags" style="zoom: 0.6;"></i>
      
      <span>Tags</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/categories" class="waves-effect waves-light">
      
      <i class="fas fa-bookmark" style="zoom: 0.6;"></i>
      
      <span>Categories</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/archives" class="waves-effect waves-light">
      
      <i class="fas fa-archive" style="zoom: 0.6;"></i>
      
      <span>Archives</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/about" class="waves-effect waves-light">
      
      <i class="fas fa-user-circle" style="zoom: 0.6;"></i>
      
      <span>About</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/contact" class="waves-effect waves-light">
      
      <i class="fas fa-comments" style="zoom: 0.6;"></i>
      
      <span>Contact</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/friends" class="waves-effect waves-light">
      
      <i class="fas fa-address-book" style="zoom: 0.6;"></i>
      
      <span>Friends</span>
    </a>
    
  </li>
  
  <li>
    <a href="#searchModal" class="modal-trigger waves-effect waves-light">
      <i id="searchIcon" class="fas fa-search" title="Search" style="zoom: 0.85;"></i>
    </a>
  </li>
</ul>


<div id="mobile-nav" class="side-nav sidenav">

    <div class="mobile-head bg-color">
        
        <img src="/medias/logo.png" class="logo-img circle responsive-img">
        
        <div class="logo-name">AverageJoe&#39;s Blog</div>
        <div class="logo-desc">
            
            this is my secret garden where I sow my inspirations.
            
        </div>
    </div>

    

    <ul class="menu-list mobile-menu-list">
        
        <li class="m-nav-item">
	  
		<a href="/" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-home"></i>
			
			Index
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/tags" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-tags"></i>
			
			Tags
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/categories" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-bookmark"></i>
			
			Categories
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/archives" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-archive"></i>
			
			Archives
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/about" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-user-circle"></i>
			
			About
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/contact" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-comments"></i>
			
			Contact
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/friends" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-address-book"></i>
			
			Friends
		</a>
          
        </li>
        
        
    </ul>
</div>


        </div>

        
    </nav>

</header>

    
<script src="/libs/cryptojs/crypto-js.min.js"></script>
<script>
    (function() {
        let pwd = '';
        if (pwd && pwd.length > 0) {
            if (pwd !== CryptoJS.SHA256(prompt('请输入访问本文章的密码')).toString(CryptoJS.enc.Hex)) {
                alert('密码错误，将返回主页！');
                location.href = '/';
            }
        }
    })();
</script>




<div class="bg-cover pd-header post-cover" style="background-image: url('/medias/featureimages/0.jpg')">
    <div class="container" style="right: 0px;left: 0px;">
        <div class="row">
            <div class="col s12 m12 l12">
                <div class="brand">
                    <h1 class="description center-align post-title"></h1>
                </div>
            </div>
        </div>
    </div>
</div>




<main class="post-container content">

    
    <link rel="stylesheet" href="/libs/tocbot/tocbot.css">
<style>
    #articleContent h1::before,
    #articleContent h2::before,
    #articleContent h3::before,
    #articleContent h4::before,
    #articleContent h5::before,
    #articleContent h6::before {
        display: block;
        content: " ";
        height: 100px;
        margin-top: -100px;
        visibility: hidden;
    }

    #articleContent :focus {
        outline: none;
    }

    .toc-fixed {
        position: fixed;
        top: 64px;
    }

    .toc-widget {
        width: 345px;
        padding-left: 20px;
    }

    .toc-widget .toc-title {
        margin: 35px 0 15px 0;
        padding-left: 17px;
        font-size: 1.5rem;
        font-weight: bold;
        line-height: 1.5rem;
    }

    .toc-widget ol {
        padding: 0;
        list-style: none;
    }

    #toc-content {
        height: calc(100vh - 250px);
        overflow: auto;
    }

    #toc-content ol {
        padding-left: 10px;
    }

    #toc-content ol li {
        padding-left: 10px;
    }

    #toc-content .toc-link:hover {
        color: #42b983;
        font-weight: 700;
        text-decoration: underline;
    }

    #toc-content .toc-link::before {
        background-color: transparent;
        max-height: 25px;

        position: absolute;
        right: 23.5vw;
        display: block;
    }

    #toc-content .is-active-link {
        color: #42b983;
    }

    #floating-toc-btn {
        position: fixed;
        right: 15px;
        bottom: 76px;
        padding-top: 15px;
        margin-bottom: 0;
        z-index: 998;
    }

    #floating-toc-btn .btn-floating {
        width: 48px;
        height: 48px;
    }

    #floating-toc-btn .btn-floating i {
        line-height: 48px;
        font-size: 1.4rem;
    }
</style>
<div class="row">
    <div id="main-content" class="col s12 m12 l9">
        <!-- 文章内容详情 -->
<div id="artDetail">
    <div class="card">
        <div class="card-content article-info">
            <div class="row tag-cate">
                <div class="col s7">
                    
                          <div class="article-tag">
                            <span class="chip bg-color">No tag</span>
                          </div>
                    
                </div>
                <div class="col s5 right-align">
                    
                </div>
            </div>

            <div class="post-info">
                
                <div class="post-date info-break-policy">
                    <i class="far fa-calendar-minus fa-fw"></i>Publish Date:&nbsp;&nbsp;
                    2018-10-21
                </div>
                

                
                <div class="post-date info-break-policy">
                    <i class="far fa-calendar-check fa-fw"></i>Update Date:&nbsp;&nbsp;
                    2018-10-21
                </div>
                

                
                <div class="info-break-policy">
                    <i class="far fa-file-word fa-fw"></i>Word Count:&nbsp;&nbsp;
                    9k
                </div>
                

                
                <div class="info-break-policy">
                    <i class="far fa-clock fa-fw"></i>Read Times:&nbsp;&nbsp;
                    37 Min
                </div>
                

                
                    <div id="busuanzi_container_page_pv" class="info-break-policy">
                        <i class="far fa-eye fa-fw"></i>Read Count:&nbsp;&nbsp;
                        <span id="busuanzi_value_page_pv"></span>
                    </div>
				
            </div>
        </div>
        <hr class="clearfix">
        <div class="card-content article-card-content">
            <div id="articleContent">
                <h1 id="0-学习目标"><a href="#0-学习目标" class="headerlink" title="0.学习目标"></a>0.学习目标</h1><ul>
<li>了解常见的MQ产品</li>
<li>了解RabbitMQ的5种消息模型</li>
<li>会使用Spring AMQP</li>
<li>利用MQ实现搜索和静态页的数据同步</li>
</ul>
<h1 id="1-RabbitMQ"><a href="#1-RabbitMQ" class="headerlink" title="1.RabbitMQ"></a>1.RabbitMQ</h1><h2 id="1-1-搜索与商品服务的问题"><a href="#1-1-搜索与商品服务的问题" class="headerlink" title="1.1.搜索与商品服务的问题"></a>1.1.搜索与商品服务的问题</h2><p>目前我们已经完成了商品详情和搜索系统的开发。我们思考一下，是否存在问题？</p>
<ul>
<li>商品的原始数据保存在数据库中，增删改查都在数据库中完成。</li>
<li>搜索服务数据来源是索引库，如果数据库商品发生变化，索引库数据不能及时更新。</li>
<li>商品详情做了页面静态化，静态页面数据也不会随着数据库商品发生变化。</li>
</ul>
<p>如果我们在后台修改了商品的价格，搜索页面和商品详情页显示的依然是旧的价格，这样显然不对。该如何解决？</p>
<p>这里有两种解决方案：</p>
<ul>
<li>方案1：每当后台对商品做增删改操作，同时要修改索引库数据及静态页面</li>
<li>方案2：搜索服务和商品页面服务对外提供操作接口，后台在商品增删改后，调用接口</li>
</ul>
<p>以上两种方式都有同一个严重问题：就是代码耦合，后台服务中需要嵌入搜索和商品页面服务，违背了微服务的<code>独立</code>原则。</p>
<p>所以，我们会通过另外一种方式来解决这个问题：消息队列</p>
<h2 id="1-2-消息队列（MQ）"><a href="#1-2-消息队列（MQ）" class="headerlink" title="1.2.消息队列（MQ）"></a>1.2.消息队列（MQ）</h2><h3 id="1-2-1-什么是消息队列"><a href="#1-2-1-什么是消息队列" class="headerlink" title="1.2.1.什么是消息队列"></a>1.2.1.什么是消息队列</h3><p>消息队列，即MQ，Message Queue。</p>
<p><img src="assets/1527063872737.png" alt="1527063872737"></p>
<p>消息队列是典型的：生产者、消费者模型。生产者不断向消息队列中生产消息，消费者不断的从队列中获取消息。因为消息的生产和消费都是异步的，而且只关心消息的发送和接收，没有业务逻辑的侵入，这样就实现了生产者和消费者的解耦。</p>
<p>结合前面所说的问题：</p>
<ul>
<li>商品服务对商品增删改以后，无需去操作索引库或静态页面，只是发送一条消息，也不关心消息被谁接收。</li>
<li>搜索服务和静态页面服务接收消息，分别去处理索引库和静态页面。</li>
</ul>
<p>如果以后有其它系统也依赖商品服务的数据，同样监听消息即可，商品服务无需任何代码修改。</p>
<h3 id="1-2-2-AMQP和JMS"><a href="#1-2-2-AMQP和JMS" class="headerlink" title="1.2.2.AMQP和JMS"></a>1.2.2.AMQP和JMS</h3><p>MQ是消息通信的模型，并不是具体实现。现在实现MQ的有两种主流方式：AMQP、JMS。</p>
<p><img src="assets/1527064480681.png" alt="1527064480681"></p>
<p><img src="assets/1527064487042.png" alt="1527064487042"></p>
<p>两者间的区别和联系：</p>
<ul>
<li>JMS是定义了统一的接口，来对消息操作进行统一；AMQP是通过规定协议来统一数据交互的格式</li>
<li>JMS限定了必须使用Java语言；AMQP只是协议，不规定实现方式，因此是跨语言的。</li>
<li>JMS规定了两种消息模型；而AMQP的消息模型更加丰富</li>
</ul>
<h3 id="1-2-3-常见MQ产品"><a href="#1-2-3-常见MQ产品" class="headerlink" title="1.2.3.常见MQ产品"></a>1.2.3.常见MQ产品</h3><p><img src="assets/1527064606029.png" alt="1527064606029"></p>
<ul>
<li>ActiveMQ：基于JMS</li>
<li>RabbitMQ：基于AMQP协议，erlang语言开发，稳定性好</li>
<li>RocketMQ：基于JMS，阿里巴巴产品，目前交由Apache基金会</li>
<li>Kafka：分布式消息系统，高吞吐量</li>
</ul>
<h3 id="1-2-4-RabbitMQ"><a href="#1-2-4-RabbitMQ" class="headerlink" title="1.2.4.RabbitMQ"></a>1.2.4.RabbitMQ</h3><p>RabbitMQ是基于AMQP的一款消息管理系统</p>
<p>官网： <a target="_blank" rel="noopener" href="http://www.rabbitmq.com/">http://www.rabbitmq.com/</a></p>
<p>官方教程：<a target="_blank" rel="noopener" href="http://www.rabbitmq.com/getstarted.html">http://www.rabbitmq.com/getstarted.html</a></p>
<p><img src="assets/1532758972119.png" alt="1532758972119"></p>
<p> <img src="assets/1527064762982.png" alt="1527064762982"></p>
<h2 id="1-3-下载和安装"><a href="#1-3-下载和安装" class="headerlink" title="1.3.下载和安装"></a>1.3.下载和安装</h2><h3 id="1-3-1-下载"><a href="#1-3-1-下载" class="headerlink" title="1.3.1.下载"></a>1.3.1.下载</h3><p>官网下载地址：<a target="_blank" rel="noopener" href="http://www.rabbitmq.com/download.html">http://www.rabbitmq.com/download.html</a></p>
<p><img src="assets/1532759070767.png" alt="1532759070767"></p>
<p>目前最新版本是：3.7.5</p>
<p>我们的课程中使用的是：3.4.1版本</p>
<p>课前资料提供了安装包：</p>
<p><img src="assets/1532761948333.png" alt="1532761948333"></p>
<h3 id="1-3-2-安装"><a href="#1-3-2-安装" class="headerlink" title="1.3.2.安装"></a>1.3.2.安装</h3><p>详见课前资料中的：</p>
<p><img src="assets/1532761916357.png" alt="1532761916357"></p>
<h1 id="2-五种消息模型"><a href="#2-五种消息模型" class="headerlink" title="2.五种消息模型"></a>2.五种消息模型</h1><p>RabbitMQ提供了6种消息模型，但是第6种其实是RPC，并不是MQ，因此不予学习。那么也就剩下5种。</p>
<p>但是其实3、4、5这三种都属于订阅模型，只不过进行路由的方式不同。</p>
<p><img src="assets/1527068544487.png" alt="1527068544487"></p>
<p>我们通过一个demo工程来了解下RabbitMQ的工作方式：</p>
<p>导入工程：</p>
<p><img src="assets/1532762038694.png" alt="1532762038694"></p>
<p>导入后：</p>
<p> <img src="assets/1532762308507.png" alt="1532762308507"></p>
<p>依赖：</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">project</span> <span class="attr">xmlns</span>=<span class="string">&quot;http://maven.apache.org/POM/4.0.0&quot;</span> <span class="attr">xmlns:xsi</span>=<span class="string">&quot;http://www.w3.org/2001/XMLSchema-instance&quot;</span></span></span><br><span class="line"><span class="tag">    <span class="attr">xsi:schemaLocation</span>=<span class="string">&quot;http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd&quot;</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">modelVersion</span>&gt;</span>4.0.0<span class="tag">&lt;/<span class="name">modelVersion</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>cn.itcast.rabbitmq<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>itcast-rabbitmq<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">version</span>&gt;</span>0.0.1-SNAPSHOT<span class="tag">&lt;/<span class="name">version</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">parent</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>org.springframework.boot<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>spring-boot-starter-parent<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">version</span>&gt;</span>2.0.2.RELEASE<span class="tag">&lt;/<span class="name">version</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">parent</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">properties</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">java.version</span>&gt;</span>1.8<span class="tag">&lt;/<span class="name">java.version</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">properties</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">dependencies</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>org.apache.commons<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>commons-lang3<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">version</span>&gt;</span>3.3.2<span class="tag">&lt;/<span class="name">version</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>org.springframework.boot<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>spring-boot-starter-amqp<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>org.springframework.boot<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>spring-boot-starter-test<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">dependencies</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">project</span>&gt;</span></span><br></pre></td></tr></table></figure>

<p>我们抽取一个建立RabbitMQ连接的工具类，方便其他程序获取连接：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">ConnectionUtil</span> </span>&#123;</span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 建立与RabbitMQ的连接</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@return</span></span></span><br><span class="line"><span class="comment">     * <span class="doctag">@throws</span> Exception</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> Connection <span class="title">getConnection</span><span class="params">()</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">        <span class="comment">//定义连接工厂</span></span><br><span class="line">        ConnectionFactory factory = <span class="keyword">new</span> ConnectionFactory();</span><br><span class="line">        <span class="comment">//设置服务地址</span></span><br><span class="line">        factory.setHost(<span class="string">&quot;192.168.56.101&quot;</span>);</span><br><span class="line">        <span class="comment">//端口</span></span><br><span class="line">        factory.setPort(<span class="number">5672</span>);</span><br><span class="line">        <span class="comment">//设置账号信息，用户名、密码、vhost</span></span><br><span class="line">        factory.setVirtualHost(<span class="string">&quot;/leyou&quot;</span>);</span><br><span class="line">        factory.setUsername(<span class="string">&quot;leyou&quot;</span>);</span><br><span class="line">        factory.setPassword(<span class="string">&quot;leyou&quot;</span>);</span><br><span class="line">        <span class="comment">// 通过工程获取连接</span></span><br><span class="line">        Connection connection = factory.newConnection();</span><br><span class="line">        <span class="keyword">return</span> connection;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<h2 id="2-1-基本消息模型"><a href="#2-1-基本消息模型" class="headerlink" title="2.1.基本消息模型"></a>2.1.基本消息模型</h2><p>官方介绍：</p>
<p> <img src="assets/1532762961149.png" alt="1532762961149"></p>
<p>RabbitMQ是一个消息代理：它接受和转发消息。 你可以把它想象成一个邮局：当你把邮件放在邮箱里时，你可以确定邮差先生最终会把邮件发送给你的收件人。 在这个比喻中，RabbitMQ是邮政信箱，邮局和邮递员。</p>
<p>RabbitMQ与邮局的主要区别是它不处理纸张，而是接受，存储和转发数据消息的二进制数据块。</p>
<p> <img src="assets/1532762975546.png" alt="1532762975546"></p>
<p>P（producer/ publisher）：生产者，一个发送消息的用户应用程序。</p>
<p>C（consumer）：消费者，消费和接收有类似的意思，消费者是一个主要用来等待接收消息的用户应用程序</p>
<p>队列（红色区域）：rabbitmq内部类似于邮箱的一个概念。虽然消息流经rabbitmq和你的应用程序，但是它们只能存储在队列中。队列只受主机的内存和磁盘限制，实质上是一个大的消息缓冲区。许多生产者可以发送消息到一个队列，许多消费者可以尝试从一个队列接收数据。</p>
<p>总之：</p>
<p>生产者将消息发送到队列，消费者从队列中获取消息，队列是存储消息的缓冲区。</p>
<p>我们将用Java编写两个程序;发送单个消息的生产者，以及接收消息并将其打印出来的消费者。我们将详细介绍Java API中的一些细节，这是一个消息传递的“Hello World”。</p>
<p>我们将调用我们的消息发布者（发送者）Send和我们的消息消费者（接收者）Recv。发布者将连接到RabbitMQ，发送一条消息，然后退出。</p>
<h3 id="2-1-1-生产者发送消息"><a href="#2-1-1-生产者发送消息" class="headerlink" title="2.1.1.生产者发送消息"></a>2.1.1.生产者发送消息</h3><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Send</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">final</span> <span class="keyword">static</span> String QUEUE_NAME = <span class="string">&quot;simple_queue&quot;</span>;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] argv)</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">        <span class="comment">// 获取到连接以及mq通道</span></span><br><span class="line">        Connection connection = ConnectionUtil.getConnection();</span><br><span class="line">        <span class="comment">// 从连接中创建通道，这是完成大部分API的地方。</span></span><br><span class="line">        Channel channel = connection.createChannel();</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 声明（创建）队列，必须声明队列才能够发送消息，我们可以把消息发送到队列中。</span></span><br><span class="line">        <span class="comment">// 声明一个队列是幂等的 - 只有当它不存在时才会被创建</span></span><br><span class="line">        channel.queueDeclare(QUEUE_NAME, <span class="keyword">false</span>, <span class="keyword">false</span>, <span class="keyword">false</span>, <span class="keyword">null</span>);</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 消息内容</span></span><br><span class="line">        String message = <span class="string">&quot;Hello World!&quot;</span>;</span><br><span class="line">        channel.basicPublish(<span class="string">&quot;&quot;</span>, QUEUE_NAME, <span class="keyword">null</span>, message.getBytes());</span><br><span class="line">        System.out.println(<span class="string">&quot; [x] Sent &#x27;&quot;</span> + message + <span class="string">&quot;&#x27;&quot;</span>);</span><br><span class="line"></span><br><span class="line">        <span class="comment">//关闭通道和连接</span></span><br><span class="line">        channel.close();</span><br><span class="line">        connection.close();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>控制台：</p>
<p><img src="assets/1532763328424.png" alt="1532763328424"></p>
<h3 id="2-1-2-管理工具中查看消息"><a href="#2-1-2-管理工具中查看消息" class="headerlink" title="2.1.2.管理工具中查看消息"></a>2.1.2.管理工具中查看消息</h3><p>进入队列页面，可以看到新建了一个队列：simple_queue</p>
<p><img src="assets/1532763817830.png" alt="1532763817830"></p>
<p>点击队列名称，进入详情页，可以查看消息：</p>
<p><img src="assets/1532763489858.png" alt="1532763489858"></p>
<p>在控制台查看消息并不会将消息消费，所以消息还在。</p>
<h3 id="2-1-3-消费者获取消息"><a href="#2-1-3-消费者获取消息" class="headerlink" title="2.1.3.消费者获取消息"></a>2.1.3.消费者获取消息</h3><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Recv</span> </span>&#123;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">final</span> <span class="keyword">static</span> String QUEUE_NAME = <span class="string">&quot;simple_queue&quot;</span>;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] argv)</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">        <span class="comment">// 获取到连接</span></span><br><span class="line">        Connection connection = ConnectionUtil.getConnection();</span><br><span class="line">        <span class="comment">// 创建通道</span></span><br><span class="line">        Channel channel = connection.createChannel();</span><br><span class="line">        <span class="comment">// 声明队列</span></span><br><span class="line">        channel.queueDeclare(QUEUE_NAME, <span class="keyword">false</span>, <span class="keyword">false</span>, <span class="keyword">false</span>, <span class="keyword">null</span>);</span><br><span class="line">        <span class="comment">// 定义队列的消费者</span></span><br><span class="line">        DefaultConsumer consumer = <span class="keyword">new</span> DefaultConsumer(channel) &#123;</span><br><span class="line">            <span class="comment">// 获取消息，并且处理，这个方法类似事件监听，如果有消息的时候，会被自动调用</span></span><br><span class="line">            <span class="meta">@Override</span></span><br><span class="line">            <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">handleDelivery</span><span class="params">(String consumerTag, Envelope envelope, BasicProperties properties,</span></span></span><br><span class="line"><span class="function"><span class="params">                    <span class="keyword">byte</span>[] body)</span> <span class="keyword">throws</span> IOException </span>&#123;</span><br><span class="line">                <span class="comment">// body 即消息体</span></span><br><span class="line">                String msg = <span class="keyword">new</span> String(body);</span><br><span class="line">                System.out.println(<span class="string">&quot; [x] received : &quot;</span> + msg + <span class="string">&quot;!&quot;</span>);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;;</span><br><span class="line">        <span class="comment">// 监听队列，第二个参数：是否自动进行消息确认。</span></span><br><span class="line">        channel.basicConsume(QUEUE_NAME, <span class="keyword">true</span>, consumer);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>控制台：</p>
<p><img src="assets/1532763733443.png" alt="1532763733443"></p>
<p>这个时候，队列中的消息就没了：</p>
<p><img src="assets/1532763773208.png" alt="1532763773208"></p>
<p>我们发现，消费者已经获取了消息，但是程序没有停止，一直在监听队列中是否有新的消息。一旦有新的消息进入队列，就会立即打印.</p>
<h3 id="2-1-4-消息确认机制（ACK）"><a href="#2-1-4-消息确认机制（ACK）" class="headerlink" title="2.1.4.消息确认机制（ACK）"></a>2.1.4.消息确认机制（ACK）</h3><p>通过刚才的案例可以看出，消息一旦被消费者接收，队列中的消息就会被删除。</p>
<p>那么问题来了：RabbitMQ怎么知道消息被接收了呢？</p>
<p>如果消费者领取消息后，还没执行操作就挂掉了呢？或者抛出了异常？消息消费失败，但是RabbitMQ无从得知，这样消息就丢失了！</p>
<p>因此，RabbitMQ有一个ACK机制。当消费者获取消息后，会向RabbitMQ发送回执ACK，告知消息已经被接收。不过这种回执ACK分两种情况：</p>
<ul>
<li>自动ACK：消息一旦被接收，消费者自动发送ACK</li>
<li>手动ACK：消息接收后，不会发送ACK，需要手动调用</li>
</ul>
<p>大家觉得哪种更好呢？</p>
<p>这需要看消息的重要性：</p>
<ul>
<li>如果消息不太重要，丢失也没有影响，那么自动ACK会比较方便</li>
<li>如果消息非常重要，不容丢失。那么最好在消费完成后手动ACK，否则接收消息后就自动ACK，RabbitMQ就会把消息从队列中删除。如果此时消费者宕机，那么消息就丢失了。</li>
</ul>
<p>我们之前的测试都是自动ACK的，如果要手动ACK，需要改动我们的代码：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Recv2</span> </span>&#123;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">final</span> <span class="keyword">static</span> String QUEUE_NAME = <span class="string">&quot;simple_queue&quot;</span>;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] argv)</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">        <span class="comment">// 获取到连接</span></span><br><span class="line">        Connection connection = ConnectionUtil.getConnection();</span><br><span class="line">        <span class="comment">// 创建通道</span></span><br><span class="line">        <span class="keyword">final</span> Channel channel = connection.createChannel();</span><br><span class="line">        <span class="comment">// 声明队列</span></span><br><span class="line">        channel.queueDeclare(QUEUE_NAME, <span class="keyword">false</span>, <span class="keyword">false</span>, <span class="keyword">false</span>, <span class="keyword">null</span>);</span><br><span class="line">        <span class="comment">// 定义队列的消费者</span></span><br><span class="line">        DefaultConsumer consumer = <span class="keyword">new</span> DefaultConsumer(channel) &#123;</span><br><span class="line">            <span class="comment">// 获取消息，并且处理，这个方法类似事件监听，如果有消息的时候，会被自动调用</span></span><br><span class="line">            <span class="meta">@Override</span></span><br><span class="line">            <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">handleDelivery</span><span class="params">(String consumerTag, Envelope envelope, BasicProperties properties,</span></span></span><br><span class="line"><span class="function"><span class="params">                    <span class="keyword">byte</span>[] body)</span> <span class="keyword">throws</span> IOException </span>&#123;</span><br><span class="line">                <span class="comment">// body 即消息体</span></span><br><span class="line">                String msg = <span class="keyword">new</span> String(body);</span><br><span class="line">                System.out.println(<span class="string">&quot; [x] received : &quot;</span> + msg + <span class="string">&quot;!&quot;</span>);</span><br><span class="line">                <span class="comment">// 手动进行ACK</span></span><br><span class="line">                channel.basicAck(envelope.getDeliveryTag(), <span class="keyword">false</span>);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;;</span><br><span class="line">        <span class="comment">// 监听队列，第二个参数false，手动进行ACK</span></span><br><span class="line">        channel.basicConsume(QUEUE_NAME, <span class="keyword">false</span>, consumer);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>注意到最后一行代码：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">channel.basicConsume(QUEUE_NAME, <span class="keyword">false</span>, consumer);</span><br></pre></td></tr></table></figure>

<p>如果第二个参数为true，则会自动进行ACK；如果为false，则需要手动ACK。方法的声明：</p>
<p><img src="assets/1532764253019.png" alt="1532764253019"></p>
<h4 id="2-1-4-1-自动ACK存在的问题"><a href="#2-1-4-1-自动ACK存在的问题" class="headerlink" title="2.1.4.1.自动ACK存在的问题"></a>2.1.4.1.自动ACK存在的问题</h4><p>修改消费者，添加异常，如下：</p>
<p><img src="assets/1532764600849.png" alt="1532764600849"></p>
<p>生产者不做任何修改，直接运行，消息发送成功：</p>
<p><img src="assets/1532764694290.png" alt="1532764694290"></p>
<p>运行消费者，程序抛出异常。但是消息依然被消费：</p>
<p><img src="assets/1532764717995.png" alt="1532764717995"></p>
<p>管理界面：</p>
<p><img src="assets/1532764734232.png" alt="1532764734232"></p>
<h4 id="2-1-4-2-演示手动ACK"><a href="#2-1-4-2-演示手动ACK" class="headerlink" title="2.1.4.2.演示手动ACK"></a>2.1.4.2.演示手动ACK</h4><p>修改消费者，把自动改成手动（去掉之前制造的异常）</p>
<p><img src="assets/1532764831241.png" alt="1532764831241"></p>
<p>生产者不变，再次运行：</p>
<p><img src="assets/1532764895239.png" alt="1532764895239"></p>
<p>运行消费者</p>
<p><img src="assets/1532764957092.png" alt="1532764957092"></p>
<p>但是，查看管理界面，发现：</p>
<p><img src="assets/1532765013834.png" alt="1532765013834"></p>
<p>停掉消费者的程序，发现：</p>
<p><img src="assets/1532765038088.png" alt="1532765038088"></p>
<p>这是因为虽然我们设置了手动ACK，但是代码中并没有进行消息确认！所以消息并未被真正消费掉。</p>
<p>当我们关掉这个消费者，消息的状态再次称为Ready</p>
<p>修改代码手动ACK：</p>
<p><img src="assets/1532765123282.png" alt="1532765123282"></p>
<p>执行：</p>
<p><img src="assets/1532765151039.png" alt="1532765151039"></p>
<p>消息消费成功！</p>
<h2 id="2-2-work消息模型"><a href="#2-2-work消息模型" class="headerlink" title="2.2.work消息模型"></a>2.2.work消息模型</h2><p>工作队列或者竞争消费者模式</p>
<p> <img src="assets/1532765197277.png" alt="1532765197277"></p>
<p>在第一篇教程中，我们编写了一个程序，从一个命名队列中发送并接受消息。在这里，我们将创建一个工作队列，在多个工作者之间分配耗时任务。</p>
<p>工作队列，又称任务队列。主要思想就是避免执行资源密集型任务时，必须等待它执行完成。相反我们稍后完成任务，我们将任务封装为消息并将其发送到队列。 在后台运行的工作进程将获取任务并最终执行作业。当你运行许多工人时，任务将在他们之间共享，但是一个消息只能被一个消费者获取。</p>
<p>这个概念在Web应用程序中特别有用，因为在短的HTTP请求窗口中无法处理复杂的任务。</p>
<p>接下来我们来模拟这个流程：</p>
<p>​    P：生产者：任务的发布者</p>
<p>​    C1：消费者，领取任务并且完成任务，假设完成速度较快</p>
<p>​    C2：消费者2：领取任务并完成任务，假设完成速度慢</p>
<p>面试题：避免消息堆积？</p>
<p>1） 采用workqueue，多个消费者监听同一队列。</p>
<p>2）接收到消息以后，而是通过线程池，异步消费。</p>
<h3 id="2-2-1-生产者"><a href="#2-2-1-生产者" class="headerlink" title="2.2.1.生产者"></a>2.2.1.生产者</h3><p>生产者与案例1中的几乎一样：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Send</span> </span>&#123;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">final</span> <span class="keyword">static</span> String QUEUE_NAME = <span class="string">&quot;test_work_queue&quot;</span>;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] argv)</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">        <span class="comment">// 获取到连接</span></span><br><span class="line">        Connection connection = ConnectionUtil.getConnection();</span><br><span class="line">        <span class="comment">// 获取通道</span></span><br><span class="line">        Channel channel = connection.createChannel();</span><br><span class="line">        <span class="comment">// 声明队列</span></span><br><span class="line">        channel.queueDeclare(QUEUE_NAME, <span class="keyword">false</span>, <span class="keyword">false</span>, <span class="keyword">false</span>, <span class="keyword">null</span>);</span><br><span class="line">        <span class="comment">// 循环发布任务</span></span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; <span class="number">50</span>; i++) &#123;</span><br><span class="line">            <span class="comment">// 消息内容</span></span><br><span class="line">            String message = <span class="string">&quot;task .. &quot;</span> + i;</span><br><span class="line">            channel.basicPublish(<span class="string">&quot;&quot;</span>, QUEUE_NAME, <span class="keyword">null</span>, message.getBytes());</span><br><span class="line">            System.out.println(<span class="string">&quot; [x] Sent &#x27;&quot;</span> + message + <span class="string">&quot;&#x27;&quot;</span>);</span><br><span class="line"></span><br><span class="line">            Thread.sleep(i * <span class="number">2</span>);</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="comment">// 关闭通道和连接</span></span><br><span class="line">        channel.close();</span><br><span class="line">        connection.close();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>不过这里我们是循环发送50条消息。</p>
<h3 id="2-2-2-消费者1"><a href="#2-2-2-消费者1" class="headerlink" title="2.2.2.消费者1"></a>2.2.2.消费者1</h3><p><img src="assets/1527085386747.png" alt="1527085386747"></p>
<h3 id="2-2-3-消费者2"><a href="#2-2-3-消费者2" class="headerlink" title="2.2.3.消费者2"></a>2.2.3.消费者2</h3><p><img src="assets/1527085448377.png" alt="1527085448377"></p>
<p>与消费者1基本类似，就是没有设置消费耗时时间。</p>
<p>这里是模拟有些消费者快，有些比较慢。</p>
<p>接下来，两个消费者一同启动，然后发送50条消息：</p>
<p><img src="assets/1527085826462.png" alt="1527085826462"></p>
<p>可以发现，两个消费者各自消费了25条消息，而且各不相同，这就实现了任务的分发。</p>
<h3 id="2-2-4-能者多劳"><a href="#2-2-4-能者多劳" class="headerlink" title="2.2.4.能者多劳"></a>2.2.4.能者多劳</h3><p>刚才的实现有问题吗？</p>
<ul>
<li>消费者1比消费者2的效率要低，一次任务的耗时较长</li>
<li>然而两人最终消费的消息数量是一样的</li>
<li>消费者2大量时间处于空闲状态，消费者1一直忙碌</li>
</ul>
<p>现在的状态属于是把任务平均分配，正确的做法应该是消费越快的人，消费的越多。</p>
<p>怎么实现呢？</p>
<p>我们可以使用basicQos方法和prefetchCount = 1设置。 这告诉RabbitMQ一次不要向工作人员发送多于一条消息。 或者换句话说，不要向工作人员发送新消息，直到它处理并确认了前一个消息。 相反，它会将其分派给不是仍然忙碌的下一个工作人员。</p>
<p><img src="assets/1532765689904.png" alt="1532765689904"></p>
<p>再次测试：</p>
<p><img src="assets/1527086159534.png" alt="1527086159534"></p>
<h2 id="2-3-订阅模型分类"><a href="#2-3-订阅模型分类" class="headerlink" title="2.3.订阅模型分类"></a>2.3.订阅模型分类</h2><p>在之前的模式中，我们创建了一个工作队列。 工作队列背后的假设是：每个任务只被传递给一个工作人员。 在这一部分，我们将做一些完全不同的事情 - 我们将会传递一个信息给多个消费者。 这种模式被称为“发布/订阅”。 </p>
<p>订阅模型示意图：</p>
<p> <img src="assets/1527086284940.png" alt="1527086284940"></p>
<p>解读：</p>
<p>1、1个生产者，多个消费者</p>
<p>2、每一个消费者都有自己的一个队列</p>
<p>3、生产者没有将消息直接发送到队列，而是发送到了交换机</p>
<p>4、每个队列都要绑定到交换机</p>
<p>5、生产者发送的消息，经过交换机到达队列，实现一个消息被多个消费者获取的目的</p>
<p>X（Exchanges）：交换机一方面：接收生产者发送的消息。另一方面：知道如何处理消息，例如递交给某个特别队列、递交给所有队列、或是将消息丢弃。到底如何操作，取决于Exchange的类型。</p>
<p>Exchange类型有以下几种：</p>
<p>​         Fanout：广播，将消息交给所有绑定到交换机的队列</p>
<p>​         Direct：定向，把消息交给符合指定routing key 的队列</p>
<p>​         Topic：通配符，把消息交给符合routing pattern（路由模式） 的队列</p>
<p>我们这里先学习</p>
<p>​    Fanout：即广播模式</p>
<p><strong>Exchange（交换机）只负责转发消息，不具备存储消息的能力</strong>，因此如果没有任何队列与Exchange绑定，或者没有符合路由规则的队列，那么消息会丢失！</p>
<h2 id="2-4-订阅模型-Fanout"><a href="#2-4-订阅模型-Fanout" class="headerlink" title="2.4.订阅模型-Fanout"></a>2.4.订阅模型-Fanout</h2><p>Fanout，也称为广播。</p>
<p>流程图：</p>
<p> <img src="assets/1527086564505.png" alt="1527086564505"></p>
<p>在广播模式下，消息发送流程是这样的：</p>
<ul>
<li>1）  可以有多个消费者</li>
<li>2）  每个<strong>消费者有自己的queue</strong>（队列）</li>
<li>3）  每个<strong>队列都要绑定到Exchange</strong>（交换机）</li>
<li>4）  <strong>生产者发送的消息，只能发送到交换机</strong>，交换机来决定要发给哪个队列，生产者无法决定。</li>
<li>5）  交换机把消息发送给绑定过的所有队列</li>
<li>6）  队列的消费者都能拿到消息。实现一条消息被多个消费者消费</li>
</ul>
<h3 id="2-4-1-生产者"><a href="#2-4-1-生产者" class="headerlink" title="2.4.1.生产者"></a>2.4.1.生产者</h3><p>两个变化：</p>
<ul>
<li>1）  声明Exchange，不再声明Queue</li>
<li>2）  发送消息到Exchange，不再发送到Queue</li>
</ul>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Send</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">final</span> <span class="keyword">static</span> String EXCHANGE_NAME = <span class="string">&quot;fanout_exchange_test&quot;</span>;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] argv)</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">        <span class="comment">// 获取到连接</span></span><br><span class="line">        Connection connection = ConnectionUtil.getConnection();</span><br><span class="line">        <span class="comment">// 获取通道</span></span><br><span class="line">        Channel channel = connection.createChannel();</span><br><span class="line">        </span><br><span class="line">        <span class="comment">// 声明exchange，指定类型为fanout</span></span><br><span class="line">        channel.exchangeDeclare(EXCHANGE_NAME, <span class="string">&quot;fanout&quot;</span>);</span><br><span class="line">        </span><br><span class="line">        <span class="comment">// 消息内容</span></span><br><span class="line">        String message = <span class="string">&quot;Hello everyone&quot;</span>;</span><br><span class="line">        <span class="comment">// 发布消息到Exchange</span></span><br><span class="line">        channel.basicPublish(EXCHANGE_NAME, <span class="string">&quot;&quot;</span>, <span class="keyword">null</span>, message.getBytes());</span><br><span class="line">        System.out.println(<span class="string">&quot; [生产者] Sent &#x27;&quot;</span> + message + <span class="string">&quot;&#x27;&quot;</span>);</span><br><span class="line"></span><br><span class="line">        channel.close();</span><br><span class="line">        connection.close();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="2-4-2-消费者1"><a href="#2-4-2-消费者1" class="headerlink" title="2.4.2.消费者1"></a>2.4.2.消费者1</h3><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Recv</span> </span>&#123;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">final</span> <span class="keyword">static</span> String QUEUE_NAME = <span class="string">&quot;fanout_exchange_queue_1&quot;</span>;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">final</span> <span class="keyword">static</span> String EXCHANGE_NAME = <span class="string">&quot;fanout_exchange_test&quot;</span>;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] argv)</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">        <span class="comment">// 获取到连接</span></span><br><span class="line">        Connection connection = ConnectionUtil.getConnection();</span><br><span class="line">        <span class="comment">// 获取通道</span></span><br><span class="line">        Channel channel = connection.createChannel();</span><br><span class="line">        <span class="comment">// 声明队列</span></span><br><span class="line">        channel.queueDeclare(QUEUE_NAME, <span class="keyword">false</span>, <span class="keyword">false</span>, <span class="keyword">false</span>, <span class="keyword">null</span>);</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 绑定队列到交换机</span></span><br><span class="line">        channel.queueBind(QUEUE_NAME, EXCHANGE_NAME, <span class="string">&quot;&quot;</span>);</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 定义队列的消费者</span></span><br><span class="line">        DefaultConsumer consumer = <span class="keyword">new</span> DefaultConsumer(channel) &#123;</span><br><span class="line">            <span class="comment">// 获取消息，并且处理，这个方法类似事件监听，如果有消息的时候，会被自动调用</span></span><br><span class="line">            <span class="meta">@Override</span></span><br><span class="line">            <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">handleDelivery</span><span class="params">(String consumerTag, Envelope envelope, BasicProperties properties,</span></span></span><br><span class="line"><span class="function"><span class="params">                    <span class="keyword">byte</span>[] body)</span> <span class="keyword">throws</span> IOException </span>&#123;</span><br><span class="line">                <span class="comment">// body 即消息体</span></span><br><span class="line">                String msg = <span class="keyword">new</span> String(body);</span><br><span class="line">                System.out.println(<span class="string">&quot; [消费者1] received : &quot;</span> + msg + <span class="string">&quot;!&quot;</span>);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;;</span><br><span class="line">        <span class="comment">// 监听队列，自动返回完成</span></span><br><span class="line">        channel.basicConsume(QUEUE_NAME, <span class="keyword">true</span>, consumer);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>要注意代码中：<strong>队列需要和交换机绑定</strong></p>
<h3 id="2-4-3-消费者2"><a href="#2-4-3-消费者2" class="headerlink" title="2.4.3.消费者2"></a>2.4.3.消费者2</h3><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Recv2</span> </span>&#123;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">final</span> <span class="keyword">static</span> String QUEUE_NAME = <span class="string">&quot;fanout_exchange_queue_2&quot;</span>;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">final</span> <span class="keyword">static</span> String EXCHANGE_NAME = <span class="string">&quot;fanout_exchange_test&quot;</span>;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] argv)</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">        <span class="comment">// 获取到连接</span></span><br><span class="line">        Connection connection = ConnectionUtil.getConnection();</span><br><span class="line">        <span class="comment">// 获取通道</span></span><br><span class="line">        Channel channel = connection.createChannel();</span><br><span class="line">        <span class="comment">// 声明队列</span></span><br><span class="line">        channel.queueDeclare(QUEUE_NAME, <span class="keyword">false</span>, <span class="keyword">false</span>, <span class="keyword">false</span>, <span class="keyword">null</span>);</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 绑定队列到交换机</span></span><br><span class="line">        channel.queueBind(QUEUE_NAME, EXCHANGE_NAME, <span class="string">&quot;&quot;</span>);</span><br><span class="line">        </span><br><span class="line">        <span class="comment">// 定义队列的消费者</span></span><br><span class="line">        DefaultConsumer consumer = <span class="keyword">new</span> DefaultConsumer(channel) &#123;</span><br><span class="line">            <span class="comment">// 获取消息，并且处理，这个方法类似事件监听，如果有消息的时候，会被自动调用</span></span><br><span class="line">            <span class="meta">@Override</span></span><br><span class="line">            <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">handleDelivery</span><span class="params">(String consumerTag, Envelope envelope, BasicProperties properties,</span></span></span><br><span class="line"><span class="function"><span class="params">                    <span class="keyword">byte</span>[] body)</span> <span class="keyword">throws</span> IOException </span>&#123;</span><br><span class="line">                <span class="comment">// body 即消息体</span></span><br><span class="line">                String msg = <span class="keyword">new</span> String(body);</span><br><span class="line">                System.out.println(<span class="string">&quot; [消费者2] received : &quot;</span> + msg + <span class="string">&quot;!&quot;</span>);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;;</span><br><span class="line">        <span class="comment">// 监听队列，手动返回完成</span></span><br><span class="line">        channel.basicConsume(QUEUE_NAME, <span class="keyword">true</span>, consumer);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<h3 id="2-4-4-测试"><a href="#2-4-4-测试" class="headerlink" title="2.4.4.测试"></a>2.4.4.测试</h3><p>我们运行两个消费者，然后发送1条消息：</p>
<p><img src="assets/1532766264386.png" alt="1532766264386"></p>
<p><img src="assets/1532766291204.png" alt="1532766291204"></p>
<h2 id="2-5-订阅模型-Direct"><a href="#2-5-订阅模型-Direct" class="headerlink" title="2.5.订阅模型-Direct"></a>2.5.订阅模型-Direct</h2><p>有选择性的接收消息</p>
<p>在订阅模式中，生产者发布消息，所有消费者都可以获取所有消息。</p>
<p>在路由模式中，我们将添加一个功能 - 我们将只能订阅一部分消息。 例如，我们只能将重要的错误消息引导到日志文件（以节省磁盘空间），同时仍然能够在控制台上打印所有日志消息。</p>
<p>但是，在某些场景下，我们希望不同的消息被不同的队列消费。这时就要用到Direct类型的Exchange。</p>
<p>在Direct模型下，队列与交换机的绑定，不能是任意绑定了，而是要指定一个RoutingKey（路由key）</p>
<p>消息的发送方在向Exchange发送消息时，也必须指定消息的routing key。</p>
<p> <img src="assets/1532766437787.png" alt="1532766437787"></p>
<p>P：生产者，向Exchange发送消息，发送消息时，会指定一个routing key。</p>
<p>X：Exchange（交换机），接收生产者的消息，然后把消息递交给 与routing key完全匹配的队列</p>
<p>C1：消费者，其所在队列指定了需要routing key 为 error 的消息</p>
<p>C2：消费者，其所在队列指定了需要routing key 为 info、error、warning 的消息</p>
<h3 id="2-5-1-生产者"><a href="#2-5-1-生产者" class="headerlink" title="2.5.1.生产者"></a>2.5.1.生产者</h3><p>此处我们模拟商品的增删改，发送消息的RoutingKey分别是：insert、update、delete</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Send</span> </span>&#123;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">final</span> <span class="keyword">static</span> String EXCHANGE_NAME = <span class="string">&quot;direct_exchange_test&quot;</span>;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] argv)</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">        <span class="comment">// 获取到连接</span></span><br><span class="line">        Connection connection = ConnectionUtil.getConnection();</span><br><span class="line">        <span class="comment">// 获取通道</span></span><br><span class="line">        Channel channel = connection.createChannel();</span><br><span class="line">        <span class="comment">// 声明exchange，指定类型为direct</span></span><br><span class="line">        channel.exchangeDeclare(EXCHANGE_NAME, <span class="string">&quot;direct&quot;</span>);</span><br><span class="line">        <span class="comment">// 消息内容</span></span><br><span class="line">        String message = <span class="string">&quot;商品新增了， id = 1001&quot;</span>;</span><br><span class="line">        <span class="comment">// 发送消息，并且指定routing key 为：insert ,代表新增商品</span></span><br><span class="line">        channel.basicPublish(EXCHANGE_NAME, <span class="string">&quot;insert&quot;</span>, <span class="keyword">null</span>, message.getBytes());</span><br><span class="line">        System.out.println(<span class="string">&quot; [商品服务：] Sent &#x27;&quot;</span> + message + <span class="string">&quot;&#x27;&quot;</span>);</span><br><span class="line"></span><br><span class="line">        channel.close();</span><br><span class="line">        connection.close();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="2-5-2-消费者1"><a href="#2-5-2-消费者1" class="headerlink" title="2.5.2.消费者1"></a>2.5.2.消费者1</h3><p>我们此处假设消费者1只接收两种类型的消息：更新商品和删除商品。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Recv</span> </span>&#123;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">final</span> <span class="keyword">static</span> String QUEUE_NAME = <span class="string">&quot;direct_exchange_queue_1&quot;</span>;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">final</span> <span class="keyword">static</span> String EXCHANGE_NAME = <span class="string">&quot;direct_exchange_test&quot;</span>;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] argv)</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">        <span class="comment">// 获取到连接</span></span><br><span class="line">        Connection connection = ConnectionUtil.getConnection();</span><br><span class="line">        <span class="comment">// 获取通道</span></span><br><span class="line">        Channel channel = connection.createChannel();</span><br><span class="line">        <span class="comment">// 声明队列</span></span><br><span class="line">        channel.queueDeclare(QUEUE_NAME, <span class="keyword">false</span>, <span class="keyword">false</span>, <span class="keyword">false</span>, <span class="keyword">null</span>);</span><br><span class="line">        </span><br><span class="line">        <span class="comment">// 绑定队列到交换机，同时指定需要订阅的routing key。假设此处需要update和delete消息</span></span><br><span class="line">        channel.queueBind(QUEUE_NAME, EXCHANGE_NAME, <span class="string">&quot;update&quot;</span>);</span><br><span class="line">        channel.queueBind(QUEUE_NAME, EXCHANGE_NAME, <span class="string">&quot;delete&quot;</span>);</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 定义队列的消费者</span></span><br><span class="line">        DefaultConsumer consumer = <span class="keyword">new</span> DefaultConsumer(channel) &#123;</span><br><span class="line">            <span class="comment">// 获取消息，并且处理，这个方法类似事件监听，如果有消息的时候，会被自动调用</span></span><br><span class="line">            <span class="meta">@Override</span></span><br><span class="line">            <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">handleDelivery</span><span class="params">(String consumerTag, Envelope envelope, BasicProperties properties,</span></span></span><br><span class="line"><span class="function"><span class="params">                    <span class="keyword">byte</span>[] body)</span> <span class="keyword">throws</span> IOException </span>&#123;</span><br><span class="line">                <span class="comment">// body 即消息体</span></span><br><span class="line">                String msg = <span class="keyword">new</span> String(body);</span><br><span class="line">                System.out.println(<span class="string">&quot; [消费者1] received : &quot;</span> + msg + <span class="string">&quot;!&quot;</span>);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;;</span><br><span class="line">        <span class="comment">// 监听队列，自动ACK</span></span><br><span class="line">        channel.basicConsume(QUEUE_NAME, <span class="keyword">true</span>, consumer);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<h3 id="2-5-3-消费者2"><a href="#2-5-3-消费者2" class="headerlink" title="2.5.3.消费者2"></a>2.5.3.消费者2</h3><p>我们此处假设消费者2接收所有类型的消息：新增商品，更新商品和删除商品。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Recv2</span> </span>&#123;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">final</span> <span class="keyword">static</span> String QUEUE_NAME = <span class="string">&quot;direct_exchange_queue_2&quot;</span>;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">final</span> <span class="keyword">static</span> String EXCHANGE_NAME = <span class="string">&quot;direct_exchange_test&quot;</span>;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] argv)</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">        <span class="comment">// 获取到连接</span></span><br><span class="line">        Connection connection = ConnectionUtil.getConnection();</span><br><span class="line">        <span class="comment">// 获取通道</span></span><br><span class="line">        Channel channel = connection.createChannel();</span><br><span class="line">        <span class="comment">// 声明队列</span></span><br><span class="line">        channel.queueDeclare(QUEUE_NAME, <span class="keyword">false</span>, <span class="keyword">false</span>, <span class="keyword">false</span>, <span class="keyword">null</span>);</span><br><span class="line">        </span><br><span class="line">        <span class="comment">// 绑定队列到交换机，同时指定需要订阅的routing key。订阅 insert、update、delete</span></span><br><span class="line">        channel.queueBind(QUEUE_NAME, EXCHANGE_NAME, <span class="string">&quot;insert&quot;</span>);</span><br><span class="line">        channel.queueBind(QUEUE_NAME, EXCHANGE_NAME, <span class="string">&quot;update&quot;</span>);</span><br><span class="line">        channel.queueBind(QUEUE_NAME, EXCHANGE_NAME, <span class="string">&quot;delete&quot;</span>);</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 定义队列的消费者</span></span><br><span class="line">        DefaultConsumer consumer = <span class="keyword">new</span> DefaultConsumer(channel) &#123;</span><br><span class="line">            <span class="comment">// 获取消息，并且处理，这个方法类似事件监听，如果有消息的时候，会被自动调用</span></span><br><span class="line">            <span class="meta">@Override</span></span><br><span class="line">            <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">handleDelivery</span><span class="params">(String consumerTag, Envelope envelope, BasicProperties properties,</span></span></span><br><span class="line"><span class="function"><span class="params">                    <span class="keyword">byte</span>[] body)</span> <span class="keyword">throws</span> IOException </span>&#123;</span><br><span class="line">                <span class="comment">// body 即消息体</span></span><br><span class="line">                String msg = <span class="keyword">new</span> String(body);</span><br><span class="line">                System.out.println(<span class="string">&quot; [消费者2] received : &quot;</span> + msg + <span class="string">&quot;!&quot;</span>);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;;</span><br><span class="line">        <span class="comment">// 监听队列，自动ACK</span></span><br><span class="line">        channel.basicConsume(QUEUE_NAME, <span class="keyword">true</span>, consumer);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<h3 id="2-5-4-测试"><a href="#2-5-4-测试" class="headerlink" title="2.5.4.测试"></a>2.5.4.测试</h3><p>我们分别发送增、删、改的RoutingKey，发现结果：</p>
<p> <img src="assets/1527088296131.png" alt="1527088296131"></p>
<h2 id="2-6-订阅模型-Topic"><a href="#2-6-订阅模型-Topic" class="headerlink" title="2.6.订阅模型-Topic"></a>2.6.订阅模型-Topic</h2><p><code>Topic</code>类型的<code>Exchange</code>与<code>Direct</code>相比，都是可以根据<code>RoutingKey</code>把消息路由到不同的队列。只不过<code>Topic</code>类型<code>Exchange</code>可以让队列在绑定<code>Routing key</code> 的时候使用通配符！</p>
<p><code>Routingkey</code> 一般都是有一个或多个单词组成，多个单词之间以”.”分割，例如： <code>item.insert</code></p>
<p> 通配符规则：</p>
<p>​         <code>#</code>：匹配一个或多个词</p>
<p>​         <code>*</code>：匹配不多不少恰好1个词</p>
<p>举例：</p>
<p>​         <code>audit.#</code>：能够匹配<code>audit.irs.corporate</code> 或者 <code>audit.irs</code></p>
<p>​         <code>audit.*</code>：只能匹配<code>audit.irs</code></p>
<p> <img src="assets/1532766712166.png" alt="1532766712166"></p>
<p>在这个例子中，我们将发送所有描述动物的消息。消息将使用由三个字（两个点）组成的routing key发送。路由关键字中的第一个单词将描述速度，第二个颜色和第三个种类：“<speed>.<color>.<species>”。</p>
<p>我们创建了三个绑定：Q1绑定了绑定键“* .orange.<em>”，Q2绑定了“</em>.*.rabbit”和“lazy.＃”。</p>
<p>Q1匹配所有的橙色动物。</p>
<p>Q2匹配关于兔子以及懒惰动物的消息。</p>
<p>练习，生产者发送如下消息，会进入那个队列：</p>
<p>quick.orange.rabbit à Q1 Q2</p>
<p>lazy.orange.elephant à Q1 Q2</p>
<p>quick.orange.fox à Q1</p>
<p>lazy.pink.rabbit à Q2</p>
<p>quick.brown.fox à 不匹配任意队列，被丢弃</p>
<p>quick.orange.male.rabbit à </p>
<p>orange à </p>
<h3 id="2-6-1-生产者"><a href="#2-6-1-生产者" class="headerlink" title="2.6.1.生产者"></a>2.6.1.生产者</h3><p>使用topic类型的Exchange，发送消息的routing key有3种： <code>item.isnert</code>、<code>item.update</code>、<code>item.delete</code>：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Send</span> </span>&#123;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">final</span> <span class="keyword">static</span> String EXCHANGE_NAME = <span class="string">&quot;topic_exchange_test&quot;</span>;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] argv)</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">        <span class="comment">// 获取到连接</span></span><br><span class="line">        Connection connection = ConnectionUtil.getConnection();</span><br><span class="line">        <span class="comment">// 获取通道</span></span><br><span class="line">        Channel channel = connection.createChannel();</span><br><span class="line">        <span class="comment">// 声明exchange，指定类型为topic</span></span><br><span class="line">        channel.exchangeDeclare(EXCHANGE_NAME, <span class="string">&quot;topic&quot;</span>);</span><br><span class="line">        <span class="comment">// 消息内容</span></span><br><span class="line">        String message = <span class="string">&quot;新增商品 : id = 1001&quot;</span>;</span><br><span class="line">        <span class="comment">// 发送消息，并且指定routing key 为：insert ,代表新增商品</span></span><br><span class="line">        channel.basicPublish(EXCHANGE_NAME, <span class="string">&quot;item.insert&quot;</span>, <span class="keyword">null</span>, message.getBytes());</span><br><span class="line">        System.out.println(<span class="string">&quot; [商品服务：] Sent &#x27;&quot;</span> + message + <span class="string">&quot;&#x27;&quot;</span>);</span><br><span class="line"></span><br><span class="line">        channel.close();</span><br><span class="line">        connection.close();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="2-6-2-消费者1"><a href="#2-6-2-消费者1" class="headerlink" title="2.6.2.消费者1"></a>2.6.2.消费者1</h3><p>我们此处假设消费者1只接收两种类型的消息：更新商品和删除商品</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Recv</span> </span>&#123;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">final</span> <span class="keyword">static</span> String QUEUE_NAME = <span class="string">&quot;topic_exchange_queue_1&quot;</span>;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">final</span> <span class="keyword">static</span> String EXCHANGE_NAME = <span class="string">&quot;topic_exchange_test&quot;</span>;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] argv)</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">        <span class="comment">// 获取到连接</span></span><br><span class="line">        Connection connection = ConnectionUtil.getConnection();</span><br><span class="line">        <span class="comment">// 获取通道</span></span><br><span class="line">        Channel channel = connection.createChannel();</span><br><span class="line">        <span class="comment">// 声明队列</span></span><br><span class="line">        channel.queueDeclare(QUEUE_NAME, <span class="keyword">false</span>, <span class="keyword">false</span>, <span class="keyword">false</span>, <span class="keyword">null</span>);</span><br><span class="line">        </span><br><span class="line">        <span class="comment">// 绑定队列到交换机，同时指定需要订阅的routing key。需要 update、delete</span></span><br><span class="line">        channel.queueBind(QUEUE_NAME, EXCHANGE_NAME, <span class="string">&quot;item.update&quot;</span>);</span><br><span class="line">        channel.queueBind(QUEUE_NAME, EXCHANGE_NAME, <span class="string">&quot;item.delete&quot;</span>);</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 定义队列的消费者</span></span><br><span class="line">        DefaultConsumer consumer = <span class="keyword">new</span> DefaultConsumer(channel) &#123;</span><br><span class="line">            <span class="comment">// 获取消息，并且处理，这个方法类似事件监听，如果有消息的时候，会被自动调用</span></span><br><span class="line">            <span class="meta">@Override</span></span><br><span class="line">            <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">handleDelivery</span><span class="params">(String consumerTag, Envelope envelope, BasicProperties properties,</span></span></span><br><span class="line"><span class="function"><span class="params">                    <span class="keyword">byte</span>[] body)</span> <span class="keyword">throws</span> IOException </span>&#123;</span><br><span class="line">                <span class="comment">// body 即消息体</span></span><br><span class="line">                String msg = <span class="keyword">new</span> String(body);</span><br><span class="line">                System.out.println(<span class="string">&quot; [消费者1] received : &quot;</span> + msg + <span class="string">&quot;!&quot;</span>);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;;</span><br><span class="line">        <span class="comment">// 监听队列，自动ACK</span></span><br><span class="line">        channel.basicConsume(QUEUE_NAME, <span class="keyword">true</span>, consumer);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<h3 id="2-6-3-消费者2"><a href="#2-6-3-消费者2" class="headerlink" title="2.6.3.消费者2"></a>2.6.3.消费者2</h3><p>我们此处假设消费者2接收所有类型的消息：新增商品，更新商品和删除商品。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 消费者2</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Recv2</span> </span>&#123;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">final</span> <span class="keyword">static</span> String QUEUE_NAME = <span class="string">&quot;topic_exchange_queue_2&quot;</span>;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">final</span> <span class="keyword">static</span> String EXCHANGE_NAME = <span class="string">&quot;topic_exchange_test&quot;</span>;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] argv)</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">        <span class="comment">// 获取到连接</span></span><br><span class="line">        Connection connection = ConnectionUtil.getConnection();</span><br><span class="line">        <span class="comment">// 获取通道</span></span><br><span class="line">        Channel channel = connection.createChannel();</span><br><span class="line">        <span class="comment">// 声明队列</span></span><br><span class="line">        channel.queueDeclare(QUEUE_NAME, <span class="keyword">false</span>, <span class="keyword">false</span>, <span class="keyword">false</span>, <span class="keyword">null</span>);</span><br><span class="line">        </span><br><span class="line">        <span class="comment">// 绑定队列到交换机，同时指定需要订阅的routing key。订阅 insert、update、delete</span></span><br><span class="line">        channel.queueBind(QUEUE_NAME, EXCHANGE_NAME, <span class="string">&quot;item.*&quot;</span>);</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 定义队列的消费者</span></span><br><span class="line">        DefaultConsumer consumer = <span class="keyword">new</span> DefaultConsumer(channel) &#123;</span><br><span class="line">            <span class="comment">// 获取消息，并且处理，这个方法类似事件监听，如果有消息的时候，会被自动调用</span></span><br><span class="line">            <span class="meta">@Override</span></span><br><span class="line">            <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">handleDelivery</span><span class="params">(String consumerTag, Envelope envelope, BasicProperties properties,</span></span></span><br><span class="line"><span class="function"><span class="params">                    <span class="keyword">byte</span>[] body)</span> <span class="keyword">throws</span> IOException </span>&#123;</span><br><span class="line">                <span class="comment">// body 即消息体</span></span><br><span class="line">                String msg = <span class="keyword">new</span> String(body);</span><br><span class="line">                System.out.println(<span class="string">&quot; [消费者2] received : &quot;</span> + msg + <span class="string">&quot;!&quot;</span>);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;;</span><br><span class="line">        <span class="comment">// 监听队列，自动ACK</span></span><br><span class="line">        channel.basicConsume(QUEUE_NAME, <span class="keyword">true</span>, consumer);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<h2 id="2-7-持久化"><a href="#2-7-持久化" class="headerlink" title="2.7.持久化"></a>2.7.持久化</h2><p>如何避免消息丢失？</p>
<p>1）  消费者的ACK机制。可以防止消费者丢失消息。</p>
<p>2）  但是，如果在消费者消费之前，MQ就宕机了，消息就没了。</p>
<p>是可以将消息进行持久化呢？</p>
<p> 要将消息持久化，前提是：队列、Exchange都持久化</p>
<h3 id="2-7-1-交换机持久化"><a href="#2-7-1-交换机持久化" class="headerlink" title="2.7.1.交换机持久化"></a>2.7.1.交换机持久化</h3><p><img src="assets/1532766951432.png" alt="1532766951432"></p>
<h3 id="2-7-2-队列持久化"><a href="#2-7-2-队列持久化" class="headerlink" title="2.7.2.队列持久化"></a>2.7.2.队列持久化</h3><p><img src="assets/1532766981230.png" alt="1532766981230"></p>
<h3 id="2-7-3-消息持久化"><a href="#2-7-3-消息持久化" class="headerlink" title="2.7.3.消息持久化"></a>2.7.3.消息持久化</h3><p><img src="assets/1532767057491.png" alt="1532767057491"></p>
<h1 id="3-Spring-AMQP"><a href="#3-Spring-AMQP" class="headerlink" title="3.Spring AMQP"></a>3.Spring AMQP</h1><h2 id="3-1-简介"><a href="#3-1-简介" class="headerlink" title="3.1.简介"></a>3.1.简介</h2><p>Sprin有很多不同的项目，其中就有对AMQP的支持：</p>
<p><img src="assets/1532767136007.png" alt="1532767136007"></p>
<p>Spring AMQP的页面：<a target="_blank" rel="noopener" href="http://spring.io/projects/spring-amqp">http://spring.io/projects/spring-amqp</a></p>
<p><img src="assets/1532767171063.png" alt="1532767171063"></p>
<p>注意这里一段描述：</p>
<p><img src="assets/1532767227821.png" alt="1532767227821">                                             </p>
<p>​         Spring-amqp是对AMQP协议的抽象实现，而spring-rabbit 是对协议的具体实现，也是目前的唯一实现。底层使用的就是RabbitMQ。</p>
<h2 id="2-2-依赖和配置"><a href="#2-2-依赖和配置" class="headerlink" title="2.2.依赖和配置"></a>2.2.依赖和配置</h2><p>添加AMQP的启动器：</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>org.springframework.boot<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>spring-boot-starter-amqp<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br></pre></td></tr></table></figure>

<p>在<code>application.yml</code>中添加RabbitMQ地址：</p>
<figure class="highlight yaml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="attr">spring:</span></span><br><span class="line">  <span class="attr">rabbitmq:</span></span><br><span class="line">    <span class="attr">host:</span> <span class="number">192.168</span><span class="number">.56</span><span class="number">.101</span></span><br><span class="line">    <span class="attr">username:</span> <span class="string">leyou</span></span><br><span class="line">    <span class="attr">password:</span> <span class="string">leyou</span></span><br><span class="line">    <span class="attr">virtual-host:</span> <span class="string">/leyou</span></span><br></pre></td></tr></table></figure>

<h2 id="2-3-监听者"><a href="#2-3-监听者" class="headerlink" title="2.3.监听者"></a>2.3.监听者</h2><p>在SpringAmqp中，对消息的消费者进行了封装和抽象，一个普通的JavaBean中的普通方法，只要通过简单的注解，就可以成为一个消费者。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Component</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Listener</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@RabbitListener(bindings = @QueueBinding(</span></span><br><span class="line"><span class="meta">            value = @Queue(value = &quot;spring.test.queue&quot;, durable = &quot;true&quot;),</span></span><br><span class="line"><span class="meta">            exchange = @Exchange(</span></span><br><span class="line"><span class="meta">                    value = &quot;spring.test.exchange&quot;,</span></span><br><span class="line"><span class="meta">                    ignoreDeclarationExceptions = &quot;true&quot;,</span></span><br><span class="line"><span class="meta">                    type = ExchangeTypes.TOPIC</span></span><br><span class="line"><span class="meta">            ),</span></span><br><span class="line"><span class="meta">            key = &#123;&quot;#.#&quot;&#125;))</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">listen</span><span class="params">(String msg)</span></span>&#123;</span><br><span class="line">        System.out.println(<span class="string">&quot;接收到消息：&quot;</span> + msg);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<ul>
<li><code>@Componet</code>：类上的注解，注册到Spring容器</li>
<li><code>@RabbitListener</code>：方法上的注解，声明这个方法是一个消费者方法，需要指定下面的属性：<ul>
<li><code>bindings</code>：指定绑定关系，可以有多个。值是<code>@QueueBinding</code>的数组。<code>@QueueBinding</code>包含下面属性：<ul>
<li><code>value</code>：这个消费者关联的队列。值是<code>@Queue</code>，代表一个队列</li>
<li><code>exchange</code>：队列所绑定的交换机，值是<code>@Exchange</code>类型</li>
<li><code>key</code>：队列和交换机绑定的<code>RoutingKey</code></li>
</ul>
</li>
</ul>
</li>
</ul>
<p>类似listen这样的方法在一个类中可以写多个，就代表多个消费者。</p>
<h2 id="2-4-AmqpTemplate"><a href="#2-4-AmqpTemplate" class="headerlink" title="2.4.AmqpTemplate"></a>2.4.AmqpTemplate</h2><p>Spring最擅长的事情就是封装，把他人的框架进行封装和整合。</p>
<p>Spring为AMQP提供了统一的消息处理模板：AmqpTemplate，非常方便的发送消息，其发送方法：</p>
<p><img src="assets/1527090258083.png" alt="1527090258083"></p>
<p>红框圈起来的是比较常用的3个方法，分别是：</p>
<ul>
<li>指定交换机、RoutingKey和消息体</li>
<li>指定消息</li>
<li>指定RoutingKey和消息，会向默认的交换机发送消息</li>
</ul>
<h2 id="2-5-测试代码"><a href="#2-5-测试代码" class="headerlink" title="2.5.测试代码"></a>2.5.测试代码</h2><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@RunWith(SpringRunner.class)</span></span><br><span class="line"><span class="meta">@SpringBootTest(classes = Application.class)</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">MqDemo</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Autowired</span></span><br><span class="line">    <span class="keyword">private</span> AmqpTemplate amqpTemplate;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Test</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">testSend</span><span class="params">()</span> <span class="keyword">throws</span> InterruptedException </span>&#123;</span><br><span class="line">        String msg = <span class="string">&quot;hello, Spring boot amqp&quot;</span>;</span><br><span class="line">        <span class="keyword">this</span>.amqpTemplate.convertAndSend(<span class="string">&quot;spring.test.exchange&quot;</span>,<span class="string">&quot;a.b&quot;</span>, msg);</span><br><span class="line">        <span class="comment">// 等待10秒后再结束</span></span><br><span class="line">        Thread.sleep(<span class="number">10000</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>运行后查看日志：</p>
<p><img src="assets/1532767726274.png" alt="1532767726274"></p>
<h1 id="3-项目改造"><a href="#3-项目改造" class="headerlink" title="3.项目改造"></a>3.项目改造</h1><p>接下来，我们就改造项目，实现搜索服务、商品静态页的数据同步。</p>
<h2 id="3-1-思路分析"><a href="#3-1-思路分析" class="headerlink" title="3.1.思路分析"></a>3.1.思路分析</h2><blockquote>
<p>发送方：商品微服务</p>
</blockquote>
<ul>
<li><p>什么时候发？</p>
<p>当商品服务对商品进行写操作：增、删、改的时候，需要发送一条消息，通知其它服务。</p>
</li>
<li><p>发送什么内容？</p>
<p>对商品的增删改时其它服务可能需要新的商品数据，但是如果消息内容中包含全部商品信息，数据量太大，而且并不是每个服务都需要全部的信息。因此我们<strong>只发送商品id</strong>，其它服务可以根据id查询自己需要的信息。</p>
</li>
</ul>
<blockquote>
<p>接收方：搜索微服务、静态页微服务</p>
</blockquote>
<p>接收消息后如何处理？</p>
<ul>
<li>搜索微服务：<ul>
<li>增/改：添加新的数据到索引库</li>
<li>删：删除索引库数据</li>
</ul>
</li>
<li>静态页微服务：<ul>
<li>增：创建新的静态页</li>
<li>删：删除原来的静态页</li>
<li>改：创建新的静态页并删除原来的</li>
</ul>
</li>
</ul>
<h2 id="3-2-商品服务发送消息"><a href="#3-2-商品服务发送消息" class="headerlink" title="3.2.商品服务发送消息"></a>3.2.商品服务发送消息</h2><p>我们先在商品微服务<code>leyou-item-service</code>中实现发送消息。</p>
<h3 id="3-2-1-引入依赖"><a href="#3-2-1-引入依赖" class="headerlink" title="3.2.1.引入依赖"></a>3.2.1.引入依赖</h3><figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>org.springframework.boot<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>spring-boot-starter-amqp<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br></pre></td></tr></table></figure>

<h3 id="3-2-2-配置文件"><a href="#3-2-2-配置文件" class="headerlink" title="3.2.2.配置文件"></a>3.2.2.配置文件</h3><p>我们在application.yml中添加一些有关RabbitMQ的配置：</p>
<figure class="highlight yaml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="attr">spring:</span></span><br><span class="line">  <span class="attr">rabbitmq:</span></span><br><span class="line">    <span class="attr">host:</span> <span class="number">192.168</span><span class="number">.56</span><span class="number">.101</span></span><br><span class="line">    <span class="attr">username:</span> <span class="string">leyou</span></span><br><span class="line">    <span class="attr">password:</span> <span class="string">leyou</span></span><br><span class="line">    <span class="attr">virtual-host:</span> <span class="string">/leyou</span></span><br><span class="line">    <span class="attr">template:</span></span><br><span class="line">      <span class="attr">exchange:</span> <span class="string">leyou.item.exchange</span></span><br><span class="line">    <span class="attr">publisher-confirms:</span> <span class="literal">true</span></span><br></pre></td></tr></table></figure>

<ul>
<li>template：有关<code>AmqpTemplate</code>的配置<ul>
<li>retry：失败重试<ul>
<li>enabled：开启失败重试</li>
<li>initial-interval：第一次重试的间隔时长</li>
<li>max-interval：最长重试间隔，超过这个间隔将不再重试</li>
<li>multiplier：下次重试间隔的倍数，此处是2即下次重试间隔是上次的2倍</li>
</ul>
</li>
<li>exchange：缺省的交换机名称，此处配置后，发送消息如果不指定交换机就会使用这个</li>
</ul>
</li>
<li>publisher-confirms：生产者确认机制，确保消息会正确发送，如果发送失败会有错误回执，从而触发重试</li>
</ul>
<h3 id="3-2-3-改造GoodsService"><a href="#3-2-3-改造GoodsService" class="headerlink" title="3.2.3.改造GoodsService"></a>3.2.3.改造GoodsService</h3><p>在GoodsService中封装一个发送消息到mq的方法：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">sendMessage</span><span class="params">(Long id, String type)</span></span>&#123;</span><br><span class="line">    <span class="comment">// 发送消息</span></span><br><span class="line">    <span class="keyword">try</span> &#123;</span><br><span class="line">        <span class="keyword">this</span>.amqpTemplate.convertAndSend(<span class="string">&quot;item.&quot;</span> + type, id);</span><br><span class="line">    &#125; <span class="keyword">catch</span> (Exception e) &#123;</span><br><span class="line">        logger.error(<span class="string">&quot;&#123;&#125;商品消息发送异常，商品id：&#123;&#125;&quot;</span>, type, id, e);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>这里没有指定交换机，因此默认发送到了配置中的：<code>leyou.item.exchange</code></p>
<p><strong>注意：这里要把所有异常都try起来，不能让消息的发送影响到正常的业务逻辑</strong></p>
<p>然后在新增的时候调用：</p>
<p><img src="assets/1532768930797.png" alt="1532768930797"></p>
<p>修改的时候调用：</p>
<p><img src="assets/1532769005960.png" alt="1532769005960"></p>
<h2 id="3-3-搜索服务接收消息"><a href="#3-3-搜索服务接收消息" class="headerlink" title="3.3.搜索服务接收消息"></a>3.3.搜索服务接收消息</h2><p>搜索服务接收到消息后要做的事情：</p>
<ul>
<li>增：添加新的数据到索引库</li>
<li>删：删除索引库数据</li>
<li>改：修改索引库数据</li>
</ul>
<p>因为索引库的新增和修改方法是合二为一的，因此我们可以将这两类消息一同处理，删除另外处理。</p>
<h3 id="3-3-1-引入依赖"><a href="#3-3-1-引入依赖" class="headerlink" title="3.3.1.引入依赖"></a>3.3.1.引入依赖</h3><figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>org.springframework.boot<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>spring-boot-starter-amqp<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br></pre></td></tr></table></figure>

<h3 id="3-3-2-添加配置"><a href="#3-3-2-添加配置" class="headerlink" title="3.3.2.添加配置"></a>3.3.2.添加配置</h3><figure class="highlight yaml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="attr">spring:</span></span><br><span class="line">  <span class="attr">rabbitmq:</span></span><br><span class="line">    <span class="attr">host:</span> <span class="number">192.168</span><span class="number">.56</span><span class="number">.101</span></span><br><span class="line">    <span class="attr">username:</span> <span class="string">leyou</span></span><br><span class="line">    <span class="attr">password:</span> <span class="string">leyou</span></span><br><span class="line">    <span class="attr">virtual-host:</span> <span class="string">/leyou</span></span><br></pre></td></tr></table></figure>

<p>这里只是接收消息而不发送，所以不用配置template相关内容。</p>
<h3 id="3-3-3-编写监听器"><a href="#3-3-3-编写监听器" class="headerlink" title="3.3.3.编写监听器"></a>3.3.3.编写监听器</h3><p> <img src="assets/1532769181819.png" alt="1532769181819"></p>
<p>代码：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Component</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">GoodsListener</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Autowired</span></span><br><span class="line">    <span class="keyword">private</span> SearchService searchService;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 处理insert和update的消息</span></span><br><span class="line"><span class="comment">     *</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> id</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@throws</span> Exception</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="meta">@RabbitListener(bindings = @QueueBinding(</span></span><br><span class="line"><span class="meta">            value = @Queue(value = &quot;leyou.create.index.queue&quot;, durable = &quot;true&quot;),</span></span><br><span class="line"><span class="meta">            exchange = @Exchange(</span></span><br><span class="line"><span class="meta">                    value = &quot;leyou.item.exchange&quot;,</span></span><br><span class="line"><span class="meta">                    ignoreDeclarationExceptions = &quot;true&quot;,</span></span><br><span class="line"><span class="meta">                    type = ExchangeTypes.TOPIC),</span></span><br><span class="line"><span class="meta">            key = &#123;&quot;item.insert&quot;, &quot;item.update&quot;&#125;))</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">listenCreate</span><span class="params">(Long id)</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">        <span class="keyword">if</span> (id == <span class="keyword">null</span>) &#123;</span><br><span class="line">            <span class="keyword">return</span>;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="comment">// 创建或更新索引</span></span><br><span class="line">        <span class="keyword">this</span>.searchService.createIndex(id);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 处理delete的消息</span></span><br><span class="line"><span class="comment">     *</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> id</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="meta">@RabbitListener(bindings = @QueueBinding(</span></span><br><span class="line"><span class="meta">            value = @Queue(value = &quot;leyou.delete.index.queue&quot;, durable = &quot;true&quot;),</span></span><br><span class="line"><span class="meta">            exchange = @Exchange(</span></span><br><span class="line"><span class="meta">                    value = &quot;leyou.item.exchange&quot;,</span></span><br><span class="line"><span class="meta">                    ignoreDeclarationExceptions = &quot;true&quot;,</span></span><br><span class="line"><span class="meta">                    type = ExchangeTypes.TOPIC),</span></span><br><span class="line"><span class="meta">            key = &quot;item.delete&quot;))</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">listenDelete</span><span class="params">(Long id)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">if</span> (id == <span class="keyword">null</span>) &#123;</span><br><span class="line">            <span class="keyword">return</span>;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="comment">// 删除索引</span></span><br><span class="line">        <span class="keyword">this</span>.searchService.deleteIndex(id);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<h3 id="3-3-4-编写创建和删除索引方法"><a href="#3-3-4-编写创建和删除索引方法" class="headerlink" title="3.3.4.编写创建和删除索引方法"></a>3.3.4.编写创建和删除索引方法</h3><p>这里因为要创建和删除索引，我们需要在SearchService中拓展两个方法，创建和删除索引：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">createIndex</span><span class="params">(Long id)</span> <span class="keyword">throws</span> IOException </span>&#123;</span><br><span class="line"></span><br><span class="line">    Spu spu = <span class="keyword">this</span>.goodsClient.querySpuById(id);</span><br><span class="line">    <span class="comment">// 构建商品</span></span><br><span class="line">    Goods goods = <span class="keyword">this</span>.buildGoods(spu);</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 保存数据到索引库</span></span><br><span class="line">    <span class="keyword">this</span>.goodsRepository.save(goods);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">deleteIndex</span><span class="params">(Long id)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">this</span>.goodsRepository.deleteById(id);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>创建索引的方法可以从之前导入数据的测试类中拷贝和改造。</p>
<h2 id="3-4-静态页服务接收消息"><a href="#3-4-静态页服务接收消息" class="headerlink" title="3.4.静态页服务接收消息"></a>3.4.静态页服务接收消息</h2><p>商品静态页服务接收到消息后的处理：</p>
<ul>
<li>增：创建新的静态页</li>
<li>删：删除原来的静态页</li>
<li>改：创建新的静态页并删除原来的</li>
</ul>
<p>不过，我们编写的创建静态页的方法也具备覆盖以前页面的功能，因此：增和改的消息可以放在一个方法中处理，删除消息放在另一个方法处理。</p>
<h3 id="3-4-1-引入依赖"><a href="#3-4-1-引入依赖" class="headerlink" title="3.4.1.引入依赖"></a>3.4.1.引入依赖</h3><figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>org.springframework.boot<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>spring-boot-starter-amqp<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br></pre></td></tr></table></figure>

<h3 id="3-4-2-添加配置"><a href="#3-4-2-添加配置" class="headerlink" title="3.4.2.添加配置"></a>3.4.2.添加配置</h3><figure class="highlight yaml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="attr">spring:</span></span><br><span class="line">  <span class="attr">rabbitmq:</span></span><br><span class="line">    <span class="attr">host:</span> <span class="number">192.168</span><span class="number">.56</span><span class="number">.101</span></span><br><span class="line">    <span class="attr">username:</span> <span class="string">leyou</span></span><br><span class="line">    <span class="attr">password:</span> <span class="string">leyou</span></span><br><span class="line">    <span class="attr">virtual-host:</span> <span class="string">/leyou</span></span><br></pre></td></tr></table></figure>

<p>这里只是接收消息而不发送，所以不用配置template相关内容。</p>
<h3 id="3-4-3-编写监听器"><a href="#3-4-3-编写监听器" class="headerlink" title="3.4.3.编写监听器"></a>3.4.3.编写监听器</h3><p> <img src="assets/1532769581964.png" alt="1532769581964"></p>
<p>代码：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Component</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">GoodsListener</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Autowired</span></span><br><span class="line">    <span class="keyword">private</span> GoodsHtmlService goodsHtmlService;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@RabbitListener(bindings = @QueueBinding(</span></span><br><span class="line"><span class="meta">            value = @Queue(value = &quot;leyou.create.web.queue&quot;, durable = &quot;true&quot;),</span></span><br><span class="line"><span class="meta">            exchange = @Exchange(</span></span><br><span class="line"><span class="meta">                    value = &quot;leyou.item.exchange&quot;,</span></span><br><span class="line"><span class="meta">                    ignoreDeclarationExceptions = &quot;true&quot;,</span></span><br><span class="line"><span class="meta">                    type = ExchangeTypes.TOPIC),</span></span><br><span class="line"><span class="meta">            key = &#123;&quot;item.insert&quot;, &quot;item.update&quot;&#125;))</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">listenCreate</span><span class="params">(Long id)</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">        <span class="keyword">if</span> (id == <span class="keyword">null</span>) &#123;</span><br><span class="line">            <span class="keyword">return</span>;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="comment">// 创建页面</span></span><br><span class="line">        goodsHtmlService.createHtml(id);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@RabbitListener(bindings = @QueueBinding(</span></span><br><span class="line"><span class="meta">            value = @Queue(value = &quot;leyou.delete.web.queue&quot;, durable = &quot;true&quot;),</span></span><br><span class="line"><span class="meta">            exchange = @Exchange(</span></span><br><span class="line"><span class="meta">                    value = &quot;leyou.item.exchange&quot;,</span></span><br><span class="line"><span class="meta">                    ignoreDeclarationExceptions = &quot;true&quot;,</span></span><br><span class="line"><span class="meta">                    type = ExchangeTypes.TOPIC),</span></span><br><span class="line"><span class="meta">            key = &quot;item.delete&quot;))</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">listenDelete</span><span class="params">(Long id)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">if</span> (id == <span class="keyword">null</span>) &#123;</span><br><span class="line">            <span class="keyword">return</span>;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="comment">// 创建页面</span></span><br><span class="line">        goodsHtmlService.deleteHtml(id);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="3-4-4-添加删除页面方法"><a href="#3-4-4-添加删除页面方法" class="headerlink" title="3.4.4.添加删除页面方法"></a>3.4.4.添加删除页面方法</h3><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">deleteHtml</span><span class="params">(Long id)</span> </span>&#123;</span><br><span class="line">    File file = <span class="keyword">new</span> File(<span class="string">&quot;C:\\project\\nginx-1.14.0\\html\\item\\&quot;</span>, id + <span class="string">&quot;.html&quot;</span>);</span><br><span class="line">    file.deleteOnExit();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<h2 id="3-5-测试"><a href="#3-5-测试" class="headerlink" title="3.5.测试"></a>3.5.测试</h2><h3 id="3-5-1-查看RabbitMQ控制台"><a href="#3-5-1-查看RabbitMQ控制台" class="headerlink" title="3.5.1.查看RabbitMQ控制台"></a>3.5.1.查看RabbitMQ控制台</h3><p>重新启动项目，并且登录RabbitMQ管理界面：<a target="_blank" rel="noopener" href="http://192.168.56.101:15672/">http://192.168.56.101:15672</a></p>
<p>可以看到，交换机已经创建出来了：</p>
<p><img src="assets/1532772446520.png" alt="1532772446520"></p>
<p>队列也已经创建完毕：</p>
<p><img src="assets/1532772471931.png" alt="1532772471931"></p>
<p>并且队列都已经绑定到交换机：</p>
<p><img src="assets/1532772521932.png" alt="1532772521932"></p>
<h3 id="3-5-2-修改数据试一试"><a href="#3-5-2-修改数据试一试" class="headerlink" title="3.5.2.修改数据试一试"></a>3.5.2.修改数据试一试</h3><p>在后台修改商品数据的价格，分别在搜索及商品详情页查看是否统一。</p>

            </div>
            <hr/>

            

    <div class="reprint" id="reprint-statement">
        
            <div class="reprint__author">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-user">
                        Author:
                    </i>
                </span>
                <span class="reprint-info">
                    <a href="/about" rel="external nofollow noreferrer">AverageJoe</a>
                </span>
            </div>
            <div class="reprint__type">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-link">
                        Link:
                    </i>
                </span>
                <span class="reprint-info">
                    <a href="http://www.averagejoe.top/2018/10/21/leyou/day15-bi-ji/day15-rabbitmq-ji-shu-ju-tong-bu/">http://www.averagejoe.top/2018/10/21/leyou/day15-bi-ji/day15-rabbitmq-ji-shu-ju-tong-bu/</a>
                </span>
            </div>
            <div class="reprint__notice">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-copyright">
                        Reprint policy:
                    </i>
                </span>
                <span class="reprint-info">
                    All articles in this blog are used except for special statements
                    <a href="https://creativecommons.org/licenses/by/4.0/deed.zh" rel="external nofollow noreferrer" target="_blank">CC BY 4.0</a>
                    reprint polocy. If reproduced, please indicate source
                    <a href="/about" target="_blank">AverageJoe</a>
                    !
                </span>
            </div>
        
    </div>

    <script async defer>
      document.addEventListener("copy", function (e) {
        let toastHTML = '<span>Copied successfully, please follow the reprint policy of this article</span><button class="btn-flat toast-action" onclick="navToReprintStatement()" style="font-size: smaller">more</a>';
        M.toast({html: toastHTML})
      });

      function navToReprintStatement() {
        $("html, body").animate({scrollTop: $("#reprint-statement").offset().top - 80}, 800);
      }
    </script>



            <div class="tag_share" style="display: block;">
                <div class="post-meta__tag-list" style="display: inline-block;">
                    
                        <div class="article-tag">
                            <span class="chip bg-color">No tag</span>
                        </div>
                    
                </div>
                <div class="post_share" style="zoom: 80%; width: fit-content; display: inline-block; float: right; margin: -0.15rem 0;">
                    <link rel="stylesheet" type="text/css" href="/libs/share/css/share.min.css">
<div id="article-share">

    
    <div class="social-share" data-sites="twitter,facebook,google,qq,qzone,wechat,weibo,douban,linkedin" data-wechat-qrcode-helper="<p>微信扫一扫即可分享！</p>"></div>
    <script src="/libs/share/js/social-share.min.js"></script>
    

    

</div>

                </div>
            </div>
            
                <style>
    #reward {
        margin: 40px 0;
        text-align: center;
    }

    #reward .reward-link {
        font-size: 1.4rem;
        line-height: 38px;
    }

    #reward .btn-floating:hover {
        box-shadow: 0 6px 12px rgba(0, 0, 0, 0.2), 0 5px 15px rgba(0, 0, 0, 0.2);
    }

    #rewardModal {
        width: 320px;
        height: 350px;
    }

    #rewardModal .reward-title {
        margin: 15px auto;
        padding-bottom: 5px;
    }

    #rewardModal .modal-content {
        padding: 10px;
    }

    #rewardModal .close {
        position: absolute;
        right: 15px;
        top: 15px;
        color: rgba(0, 0, 0, 0.5);
        font-size: 1.3rem;
        line-height: 20px;
        cursor: pointer;
    }

    #rewardModal .close:hover {
        color: #ef5350;
        transform: scale(1.3);
        -moz-transform:scale(1.3);
        -webkit-transform:scale(1.3);
        -o-transform:scale(1.3);
    }

    #rewardModal .reward-tabs {
        margin: 0 auto;
        width: 210px;
    }

    .reward-tabs .tabs {
        height: 38px;
        margin: 10px auto;
        padding-left: 0;
    }

    .reward-content ul {
        padding-left: 0 !important;
    }

    .reward-tabs .tabs .tab {
        height: 38px;
        line-height: 38px;
    }

    .reward-tabs .tab a {
        color: #fff;
        background-color: #ccc;
    }

    .reward-tabs .tab a:hover {
        background-color: #ccc;
        color: #fff;
    }

    .reward-tabs .wechat-tab .active {
        color: #fff !important;
        background-color: #22AB38 !important;
    }

    .reward-tabs .alipay-tab .active {
        color: #fff !important;
        background-color: #019FE8 !important;
    }

    .reward-tabs .reward-img {
        width: 210px;
        height: 210px;
    }
</style>

<div id="reward">
    <a href="#rewardModal" class="reward-link modal-trigger btn-floating btn-medium waves-effect waves-light red">赏</a>

    <!-- Modal Structure -->
    <div id="rewardModal" class="modal">
        <div class="modal-content">
            <a class="close modal-close"><i class="fas fa-times"></i></a>
            <h4 class="reward-title">你的赏识是我前进的动力</h4>
            <div class="reward-content">
                <div class="reward-tabs">
                    <ul class="tabs row">
                        <li class="tab col s6 alipay-tab waves-effect waves-light"><a href="#alipay">支付宝</a></li>
                        <li class="tab col s6 wechat-tab waves-effect waves-light"><a href="#wechat">微 信</a></li>
                    </ul>
                    <div id="alipay">
                        <img src="/medias/reward/alipay.jpg" class="reward-img" alt="支付宝打赏二维码">
                    </div>
                    <div id="wechat">
                        <img src="/medias/reward/wechat.png" class="reward-img" alt="微信打赏二维码">
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
    $(function () {
        $('.tabs').tabs();
    });
</script>

            
        </div>
    </div>

    

    

    

    

    
        <style>
    .valine-card {
        margin: 1.5rem auto;
    }

    .valine-card .card-content {
        padding: 20px 20px 5px 20px;
    }

    #vcomments textarea {
        box-sizing: border-box;
        background: url("/medias/comment_bg.png") 100% 100% no-repeat;
    }

    #vcomments p {
        margin: 2px 2px 10px;
        font-size: 1.05rem;
        line-height: 1.78rem;
    }

    #vcomments blockquote p {
        text-indent: 0.2rem;
    }

    #vcomments a {
        padding: 0 2px;
        color: #4cbf30;
        font-weight: 500;
        text-decoration: none;
    }

    #vcomments img {
        max-width: 100%;
        height: auto;
        cursor: pointer;
    }

    #vcomments ol li {
        list-style-type: decimal;
    }

    #vcomments ol,
    ul {
        display: block;
        padding-left: 2em;
        word-spacing: 0.05rem;
    }

    #vcomments ul li,
    ol li {
        display: list-item;
        line-height: 1.8rem;
        font-size: 1rem;
    }

    #vcomments ul li {
        list-style-type: disc;
    }

    #vcomments ul ul li {
        list-style-type: circle;
    }

    #vcomments table, th, td {
        padding: 12px 13px;
        border: 1px solid #dfe2e5;
    }

    #vcomments table, th, td {
        border: 0;
    }

    table tr:nth-child(2n), thead {
        background-color: #fafafa;
    }

    #vcomments table th {
        background-color: #f2f2f2;
        min-width: 80px;
    }

    #vcomments table td {
        min-width: 80px;
    }

    #vcomments h1 {
        font-size: 1.85rem;
        font-weight: bold;
        line-height: 2.2rem;
    }

    #vcomments h2 {
        font-size: 1.65rem;
        font-weight: bold;
        line-height: 1.9rem;
    }

    #vcomments h3 {
        font-size: 1.45rem;
        font-weight: bold;
        line-height: 1.7rem;
    }

    #vcomments h4 {
        font-size: 1.25rem;
        font-weight: bold;
        line-height: 1.5rem;
    }

    #vcomments h5 {
        font-size: 1.1rem;
        font-weight: bold;
        line-height: 1.4rem;
    }

    #vcomments h6 {
        font-size: 1rem;
        line-height: 1.3rem;
    }

    #vcomments p {
        font-size: 1rem;
        line-height: 1.5rem;
    }

    #vcomments hr {
        margin: 12px 0;
        border: 0;
        border-top: 1px solid #ccc;
    }

    #vcomments blockquote {
        margin: 15px 0;
        border-left: 5px solid #42b983;
        padding: 1rem 0.8rem 0.3rem 0.8rem;
        color: #666;
        background-color: rgba(66, 185, 131, .1);
    }

    #vcomments pre {
        font-family: monospace, monospace;
        padding: 1.2em;
        margin: .5em 0;
        background: #272822;
        overflow: auto;
        border-radius: 0.3em;
        tab-size: 4;
    }

    #vcomments code {
        font-family: monospace, monospace;
        padding: 1px 3px;
        font-size: 0.92rem;
        color: #e96900;
        background-color: #f8f8f8;
        border-radius: 2px;
    }

    #vcomments pre code {
        font-family: monospace, monospace;
        padding: 0;
        color: #e8eaf6;
        background-color: #272822;
    }

    #vcomments pre[class*="language-"] {
        padding: 1.2em;
        margin: .5em 0;
    }

    #vcomments code[class*="language-"],
    pre[class*="language-"] {
        color: #e8eaf6;
    }

    #vcomments [type="checkbox"]:not(:checked), [type="checkbox"]:checked {
        position: inherit;
        margin-left: -1.3rem;
        margin-right: 0.4rem;
        margin-top: -1px;
        vertical-align: middle;
        left: unset;
        visibility: visible;
    }

    #vcomments b,
    strong {
        font-weight: bold;
    }

    #vcomments dfn {
        font-style: italic;
    }

    #vcomments small {
        font-size: 85%;
    }

    #vcomments cite {
        font-style: normal;
    }

    #vcomments mark {
        background-color: #fcf8e3;
        padding: .2em;
    }

    #vcomments table, th, td {
        padding: 12px 13px;
        border: 1px solid #dfe2e5;
    }

    table tr:nth-child(2n), thead {
        background-color: #fafafa;
    }

    #vcomments table th {
        background-color: #f2f2f2;
        min-width: 80px;
    }

    #vcomments table td {
        min-width: 80px;
    }

    #vcomments [type="checkbox"]:not(:checked), [type="checkbox"]:checked {
        position: inherit;
        margin-left: -1.3rem;
        margin-right: 0.4rem;
        margin-top: -1px;
        vertical-align: middle;
        left: unset;
        visibility: visible;
    }
</style>

<div class="card valine-card" data-aos="fade-up">
    <div class="comment_headling" style="font-size: 20px; font-weight: 700; position: relative; padding-left: 20px; top: 15px; padding-bottom: 5px;">
        <i class="fas fa-comments fa-fw" aria-hidden="true"></i>
        <span>评论</span>
    </div>
    <div id="vcomments" class="card-content" style="display: grid">
    </div>
</div>

<script src="/libs/valine/av-min.js"></script>
<script src="/libs/valine/Valine.min.js"></script>
<script>
    new Valine({
        el: '#vcomments',
        appId: 'BhOC9gMKAfPsRTjqr679tX7A-gzGzoHsz',
        appKey: 'xb9C1I9k62m6AJvin0UWGhSr',
        notify: 'false' === 'true',
        verify: 'false' === 'true',
        visitor: 'true' === 'true',
        avatar: 'mm',
        pageSize: '10',
        lang: 'en',
        placeholder: 'just go go'
    });
</script>

    

    

    

<article id="prenext-posts" class="prev-next articles">
    <div class="row article-row">
        
        <div class="article col s12 m6" data-aos="fade-up">
            <div class="article-badge left-badge text-color">
                <i class="fas fa-chevron-left"></i>&nbsp;Previous</div>
            <div class="card">
                <a href="/2018/10/24/leyou/day17-bi-ji/day17-shou-quan-zhong-xin/">
                    <div class="card-image">
                        
                        
                        <img src="/medias/featureimages/0.jpg" class="responsive-img" alt="">
                        
                        <span class="card-title"></span>
                    </div>
                </a>
                <div class="card-content article-content">
                    <div class="summary block-with-text">
                        
                            0.学习目标1.无状态登录原理1.1.什么是有状态？有状态服务，即服务端需要记录每次会话的客户端信息，从而识别客户端身份，根据用户身份进行请求的处理，典型的设计如tomcat中的session。
例如登录：用户登录后，我们把登录者的信息保存
                        
                    </div>
                    <div class="publish-info">
                        <span class="publish-date">
                            <i class="far fa-clock fa-fw icon-date"></i>2018-10-24
                        </span>
                        <span class="publish-author">
                            
                            <i class="fas fa-user fa-fw"></i>
                            AverageJoe
                            
                        </span>
                    </div>
                </div>
                
            </div>
        </div>
        
        
        <div class="article col s12 m6" data-aos="fade-up">
            <div class="article-badge right-badge text-color">
                Next&nbsp;<i class="fas fa-chevron-right"></i>
            </div>
            <div class="card">
                <a href="/2018/10/19/leyou/day14-bi-ji/day14.shang-pin-xiang-qing-ji-jing-tai-hua/">
                    <div class="card-image">
                        
                        
                        <img src="/medias/featureimages/0.jpg" class="responsive-img" alt="">
                        
                        <span class="card-title"></span>
                    </div>
                </a>
                <div class="card-content article-content">
                    <div class="summary block-with-text">
                        
                            0.学习目标
了解Thymeleaf的基本使用
实现商品详情页的渲染
知道页面静态化的作用
实现页面静态化功能

1.商品详情当用户搜索到商品，肯定会点击查看，就会进入商品详情页，接下来我们完成商品详情页的展示，
1.1.Thymeleaf
                        
                    </div>
                    <div class="publish-info">
                            <span class="publish-date">
                                <i class="far fa-clock fa-fw icon-date"></i>2018-10-19
                            </span>
                        <span class="publish-author">
                            
                            <i class="fas fa-user fa-fw"></i>
                            AverageJoe
                            
                        </span>
                    </div>
                </div>
                
            </div>
        </div>
        
    </div>
</article>

</div>



<!-- 代码块功能依赖 -->
<script type="text/javascript" src="/libs/codeBlock/codeBlockFuction.js"></script>

<!-- 代码语言 -->

<script type="text/javascript" src="/libs/codeBlock/codeLang.js"></script>


<!-- 代码块复制 -->

<script type="text/javascript" src="/libs/codeBlock/codeCopy.js"></script>


<!-- 代码块收缩 -->

<script type="text/javascript" src="/libs/codeBlock/codeShrink.js"></script>


<!-- 代码块折行 -->

<style type="text/css">
code[class*="language-"], pre[class*="language-"] { white-space: pre !important; }
</style>


    </div>
    <div id="toc-aside" class="expanded col l3 hide-on-med-and-down">
        <div class="toc-widget">
            <div class="toc-title"><i class="far fa-list-alt"></i>&nbsp;&nbsp;TOC</div>
            <div id="toc-content"></div>
        </div>
    </div>
</div>

<!-- TOC 悬浮按钮. -->

<div id="floating-toc-btn" class="hide-on-med-and-down">
    <a class="btn-floating btn-large bg-color">
        <i class="fas fa-list-ul"></i>
    </a>
</div>


<script src="/libs/tocbot/tocbot.min.js"></script>
<script>
    $(function () {
        tocbot.init({
            tocSelector: '#toc-content',
            contentSelector: '#articleContent',
            headingsOffset: -($(window).height() * 0.4 - 45),
            collapseDepth: Number('0'),
            headingSelector: 'h2, h3, h4'
        });

        // modify the toc link href to support Chinese.
        let i = 0;
        let tocHeading = 'toc-heading-';
        $('#toc-content a').each(function () {
            $(this).attr('href', '#' + tocHeading + (++i));
        });

        // modify the heading title id to support Chinese.
        i = 0;
        $('#articleContent').children('h2, h3, h4').each(function () {
            $(this).attr('id', tocHeading + (++i));
        });

        // Set scroll toc fixed.
        let tocHeight = parseInt($(window).height() * 0.4 - 64);
        let $tocWidget = $('.toc-widget');
        $(window).scroll(function () {
            let scroll = $(window).scrollTop();
            /* add post toc fixed. */
            if (scroll > tocHeight) {
                $tocWidget.addClass('toc-fixed');
            } else {
                $tocWidget.removeClass('toc-fixed');
            }
        });

        
        /* 修复文章卡片 div 的宽度. */
        let fixPostCardWidth = function (srcId, targetId) {
            let srcDiv = $('#' + srcId);
            if (srcDiv.length === 0) {
                return;
            }

            let w = srcDiv.width();
            if (w >= 450) {
                w = w + 21;
            } else if (w >= 350 && w < 450) {
                w = w + 18;
            } else if (w >= 300 && w < 350) {
                w = w + 16;
            } else {
                w = w + 14;
            }
            $('#' + targetId).width(w);
        };

        // 切换TOC目录展开收缩的相关操作.
        const expandedClass = 'expanded';
        let $tocAside = $('#toc-aside');
        let $mainContent = $('#main-content');
        $('#floating-toc-btn .btn-floating').click(function () {
            if ($tocAside.hasClass(expandedClass)) {
                $tocAside.removeClass(expandedClass).hide();
                $mainContent.removeClass('l9');
            } else {
                $tocAside.addClass(expandedClass).show();
                $mainContent.addClass('l9');
            }
            fixPostCardWidth('artDetail', 'prenext-posts');
        });
        
    });
</script>

    

</main>




    <footer class="page-footer bg-color">
    
        <link rel="stylesheet" href="/libs/aplayer/APlayer.min.css">
<style>
    .aplayer .aplayer-lrc p {
        
        display: none;
        
        font-size: 12px;
        font-weight: 700;
        line-height: 16px !important;
    }

    .aplayer .aplayer-lrc p.aplayer-lrc-current {
        
        display: none;
        
        font-size: 15px;
        color: #42b983;
    }

    
    .aplayer.aplayer-fixed.aplayer-narrow .aplayer-body {
        left: -66px !important;
    }

    .aplayer.aplayer-fixed.aplayer-narrow .aplayer-body:hover {
        left: 0px !important;
    }

    
</style>
<div class="">
    
    <div class="row">
        <meting-js class="col l8 offset-l2 m10 offset-m1 s12"
                   server="netease"
                   type="playlist"
                   id="503838841"
                   fixed='true'
                   autoplay='false'
                   theme='#42b983'
                   loop='all'
                   order='random'
                   preload='auto'
                   volume='0.7'
                   list-folded='true'
        >
        </meting-js>
    </div>
</div>

<script src="/libs/aplayer/APlayer.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/meting@2/dist/Meting.min.js"></script>

    
    <div class="container row center-align" style="margin-bottom: 0px !important;">
        <div class="col s12 m8 l8 copy-right">
            Copyright&nbsp;&copy;
            <span id="year">2019</span>
            <a href="/about" target="_blank">AverageJoe</a>
            |&nbsp;Powered by&nbsp;<a href="#" target="_blank">AverageJoe</a>
            |&nbsp;Theme&nbsp;<a href="#" target="_blank">Matery</a>
            <br>
            
            &nbsp;<i class="fas fa-chart-area"></i>&nbsp;站点总字数:&nbsp;<span
                class="white-color">213.1k</span>&nbsp;字
            
            
            
            
            
            
            <span id="busuanzi_container_site_pv">
                |&nbsp;<i class="far fa-eye"></i>&nbsp;总访问量:&nbsp;<span id="busuanzi_value_site_pv"
                    class="white-color"></span>&nbsp;次
            </span>
            
            
            <span id="busuanzi_container_site_uv">
                |&nbsp;<i class="fas fa-users"></i>&nbsp;总访问人数:&nbsp;<span id="busuanzi_value_site_uv"
                    class="white-color"></span>&nbsp;人
            </span>
            
            <br>
            
            <br>
            
        </div>
        <div class="col s12 m4 l4 social-link social-statis">


    <a href="mailto:1533360044@qq.com" class="tooltipped" target="_blank" data-tooltip="邮件联系我" data-position="top" data-delay="50">
        <i class="fas fa-envelope-open"></i>
    </a>







    <a href="tencent://AddContact/?fromId=50&fromSubId=1&subcmd=all&uin=1533360044" class="tooltipped" target="_blank" data-tooltip="QQ联系我: 1533360044" data-position="top" data-delay="50">
        <i class="fab fa-qq"></i>
    </a>







    <a href="/atom.xml" class="tooltipped" target="_blank" data-tooltip="RSS 订阅" data-position="top" data-delay="50">
        <i class="fas fa-rss"></i>
    </a>

</div>
    </div>
</footer>

<div class="progress-bar"></div>


    <!-- 搜索遮罩框 -->
<div id="searchModal" class="modal">
    <div class="modal-content">
        <div class="search-header">
            <span class="title"><i class="fas fa-search"></i>&nbsp;&nbsp;Search</span>
            <input type="search" id="searchInput" name="s" placeholder="Please enter a search keyword"
                   class="search-input">
        </div>
        <div id="searchResult"></div>
    </div>
</div>

<script src="/js/search.js"></script>
<script type="text/javascript">
$(function () {
    searchFunc("/search.xml", 'searchInput', 'searchResult');
});
</script>

    <!-- 回到顶部按钮 -->
<div id="backTop" class="top-scroll">
    <a class="btn-floating btn-large waves-effect waves-light" href="#!">
        <i class="fas fa-arrow-up"></i>
    </a>
</div>


    <script src="/libs/materialize/materialize.min.js"></script>
    <script src="/libs/masonry/masonry.pkgd.min.js"></script>
    <script src="/libs/aos/aos.js"></script>
    <script src="/libs/scrollprogress/scrollProgress.min.js"></script>
    <script src="/libs/lightGallery/js/lightgallery-all.min.js"></script>
    <script src="/js/matery.js"></script>

    <!-- Baidu Analytics -->

    <!-- Baidu Push -->

<script>
    (function () {
        var bp = document.createElement('script');
        var curProtocol = window.location.protocol.split(':')[0];
        if (curProtocol === 'https') {
            bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';
        } else {
            bp.src = 'http://push.zhanzhang.baidu.com/push.js';
        }
        var s = document.getElementsByTagName("script")[0];
        s.parentNode.insertBefore(bp, s);
    })();
</script>

    
    <script src="/libs/others/clicklove.js" async="async"></script>
    
    
    <script async src="/libs/others/busuanzi.pure.mini.js"></script>
    

    

    

    

    

    

    
    <script src="/libs/instantpage/instantpage.js" type="module"></script>
    
	

	<div id="weather-v2-plugin-simple"></div>
<script>
WIDGET = {
  CONFIG: {
    "modules": "0124",
    "background": 1,
    "tmpColor": "FFFFFF",
    "tmpSize": 16,
    "cityColor": "FFFFFF",
    "citySize": 16,
    "aqiSize": 16,
    "weatherIconSize": 24,
    "alertIconSize": 18,
    "padding": "10px 10px 10px 10px",
    "shadow": "1",
    "language": "auto",
    "borderRadius": 5,
    "fixed": "false",
    "vertical": "middle",
    "horizontal": "center",
    "key": "XZgo8dbNqo"
  }
}
</script>
<script src="https://apip.weatherdt.com/simple/static/js/weather-simple-common.js?v=2.0"></script>
<script src="/js/cursor.js"></script>
</body>

</html>
